I saw that Leila Hamon is already linked to this article on emulating infix operators in JS .
But I thought an example might be useful to others.
Here's how you could hack Number and Boolean prototypes to handle seconded infix expressions like 4 < 5 < 10 .
You can expand this by adding more methods for more prototypes. This is a bit ugly, but can be useful in order to make queries less verbose.
//Usage code (4) .gt (6) .gt (4) //false (100) .lt (200) .lt (400) . gt(0) . gt(-1)//true (100) [ '>' ] (50) [ '<' ] (20)//false //Setup Code (function(){ var lastVal = null; var nP = Number.prototype var bP = Boolean.prototype nP.gt = function(other){ lastVal = other; return this > other; } nP.lt = function(other){ lastVal = other; return this < other; } bP.gt = function(other){ var result = lastVal > other; lastVal = other; return result; } bP.lt = function(other){ var result = lastVal < other; lastVal = other; return result; } bP['<'] = bP.lt bP['>'] = bP.gt nP['<'] = nP.lt nP['>'] = nP.gt })()
James forbes
source share