I'm working on a random code challenge, and I cannot figure out for the life of me how this would be possible
function(obj) {
if ( (obj < 10) && (obj > 10) ) {
return true;
}
}
Things I've tried are setting an interval to change the variable at 0ms(which ends up being browser default), making obj an life function that increments a global variable every time it's used, and a whole bunch of other seemingly less useful approaches. Any ideas here, or pointers for something obvious I'm missing?
The clue is in the variable name "obj". When objects are compared, their valueOf()
method is called. If we supply a valueOf
method that returns a different value every time:
function test(obj) {
if ( (obj < 10) && (obj > 10) ) {
return true;
}
}
var Obj = function() {
var flag = false;
this.valueOf = function() {
if( flag ) {
return 11;
}
flag = true;
return 9;
}
}
console.log( test( new Obj() ) );
The above object's toValue
returns 9 the first time it's called (9 < 10) and 11 from then on (11 > 10).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With