Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

123
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda