Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Less than and greater than 10

Tags:

javascript

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?

like image 978
Doug Leary Avatar asked Oct 29 '16 19:10

Doug Leary


1 Answers

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).

like image 106
JJJ Avatar answered Oct 06 '22 18:10

JJJ