Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

124
Vistas
Can a JavaScript variable be true N times and then false?

Is it possible to have a JavaScript variable that, when used by other code, works as a boolean (a single bit of memory) but has an internal state so that it is true the first N times that the value is read, and then false?

In other words, is it possible to define trueNTimes so that the following code prints yes 3 times and then prints no 2 times?

let true3times = trueNTimes(3);
for (let i = 5; i; --i)
    if (true3times) console.log('yes');
    else console.log('no');

As as a side note, it can be done in C++ (by defining struct TrueNTimes with operator bool) like this:

#include <iostream>
struct TrueNTimes {
    TrueNTimes(uint const N) : n(N) {}
    operator bool() {
        if (n) {
            --n; 
            return true;
        }
        return false;
    }
private:
    uint n;
};

int main() {
    TrueNTimes true3times(3);
    for (uint i = 5; i; --i)
        if (true3times) std::cout << "yes\n";
        else std::cout << "no\n";
}

The C++ compiler finds a variable of type struct TrueNTimes where a bool is needed and will therefore use the provided TrueNTimes::operator bool.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Yes, in JavaScript you would define valueOf:

function trueNTimes(n) {
    return {
        valueOf() {
            if (n) {
                --n; 
                return true;
            } else 
                return false;
        }
    }
};

let true3times = trueNTimes(3);
console.log(true3times + ' ' + true3times + ' ' + true3times + ' ' + true3times + ' ' + true3times);

As in JavaScript objects are always truthy, you need to really compare this variable in order to trigger the valueOf algorithm:

function trueNTimes(n) {
    return {
        valueOf() {
            if (n) {
                --n; 
                return true;
            } else 
                return false;
        }
    }
};

let true3times = trueNTimes(3);
for (let i = 5; i; --i)
    if (true3times == true) console.log('yes');
    else console.log('no');

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda