Turn js operators into delicious first-class functions.
var lift = require('op-lift')
;[1, 2, 3, 4].reduce(lift('+')) //= 10
install via npm: npm install op-lift
test: cd node_modules/op-lift && npm test
Requires an es5, or es5-shim for older engines.
lift takes a string representing an operator, and returns a function that performs the same job.
var lift = require('op-lift')
;[1, 2, 3, 4].reduce(lift('*')) //= 24
;[true, false, true].map(lift('!')) //= [ false, true, false ]
;[Object, Array, Function].map(lift('new')).map(lift('typeof')) //= [ 'object', 'object', 'function' ]
It's safe to use with arbitrary strings, too, since lift will simply return null
for unrecognised operators:
lift('; console.log(a), a +') //= null
The supported operators are:
prefix: void typeof ++ -- + - ~ ! new
infix: * / % + - << >> >>> < > <= >= instanceof in == != === !== & ^ | || && . ,
postfix: ()
weirdfix: ?:
Since the resulting functions simply accept values as arguments, no short-circuiting can be done:
lift('||')(false, alert('BOO')) // an alert still shows up with 'BOO'
Any operator that affects a variables' value won't in its lifted form:
var a = 0
lift('++')(a) // 1
a // 0
Since the primary difference between operators and functions is that functions are first class, op-lift works very well with libraries heavy on the higher-order functions, including:
- tap - allows functions to be injected into the method chain
- underscore - uses functional iterators, and has standard functional partial application & composition.