Last active
August 29, 2015 14:28
-
-
Save dtipson/7c4dce0c7f9452b6098a to your computer and use it in GitHub Desktop.
composable lensOver constructs w/ Immutable.js instead of lodash's deepClone
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function curry(fx) { | |
var arity = fx.length; | |
return function f1() { | |
var args = Array.prototype.slice.call(arguments, 0); | |
if (args.length >= arity) { | |
return fx.apply(null, args); | |
} | |
else { | |
return function f2() { | |
var args2 = Array.prototype.slice.call(arguments, 0); | |
return f1.apply(null, args.concat(args2)); | |
} | |
} | |
}; | |
} | |
function simpleCompose(fn1,fn2){ | |
return function(x){ | |
return fn1(fn2(x)); | |
} | |
} | |
var lensOver = curry(function(keypath, fn, imobj){ | |
keypath = typeof keypath === "string"?[keypath]:keypath; | |
return imobj.hasIn(keypath) ? | |
imobj.setIn(keypath, fn(imobj.getIn(keypath))) : | |
imobj; | |
}); | |
var example = Immutable.fromJS({name:'guy',job:{role:'dev',employer:'BSD'}}), | |
toUpper = function(str){return str.toUpperCase();} | |
var upperName = lensOver('name',toUpper), | |
fixDev = lensOver(['job','role'],function(str){return str.replace('dev','Developer')}); | |
upperName(example).toJS();//returns {name:'GUY',job:{role:'dev',employer:'BSD'}} | |
fixDev(example).toJS();// returns {name:'guy',job:{role:'Developer',employer:'BSD'}} | |
simpleCompose(upperName,fixDev)(example).toJS();// returns {name:'GUY',job:{role:'Developer',employer:'BSD'}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment