'Can a JavaScript variable be true N times and then false? [closed]
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.
Solution 1:[1]
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');
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
