Skip to content

Instantly share code, notes, and snippets.

@nfeldman
Created September 3, 2011 02:47
Show Gist options
  • Save nfeldman/1190459 to your computer and use it in GitHub Desktop.
Save nfeldman/1190459 to your computer and use it in GitHub Desktop.
demonstration of function composition using Fortinbras components
/**
* Standalone demonstration of function composition using Fortinbras components
* Paste into a browser console and run. (Bonus demo: safe use of ASI)
* @author Noah Feldman
*/
// basic compose looks like: compose(f, g) (x) = f(g(x))
// or: apply argFunc to the arguments, then apply func to the result
// mine does the same thing, but let's us supply extra arguments
function compose (func, argFunc, thisObj) {
return function () { // call argFunc with as many of the arguments as it can use, then call func with the result plus any remaining arguments
return func.apply(thisObj, concat.call([argFunc.apply(thisObj, arguments)], splice.call(arguments, argFunc.length, arguments.length)))
}
}
var splice = Array.prototype.splice,
concat = Array.prototype.concat,
exists = (function (U) {
return function (obj, prop) {
var idx;
if (prop === '' && obj)
return true
if (obj) {
idx = prop.indexOf('.')
if (idx > -1)
return (obj = obj[prop.slice(0, idx)]) === U ? false : exists(obj, prop.slice(++idx, prop.length))
else
return typeof obj[prop] != 'undefined' && obj[prop] !== U
}
return false
}
}()),
isGetValue = function (a, b) {
var nest, len
if (exists(a, b)) {
nest = b.split('.').reverse()
len = nest.length
while (--len)
a = a[nest[len]]
return a[nest[0]]
}
return false
},
propEql = compose(function (a, b) { return a === b }, isGetValue)
// CONSOLE TEST
// GIVEN
var t = {foo: {bar: {baz: {say: 'hello'}}}}
// THEN
propEql(t, 'foo.bar.baz.say', 'hello') === true
// BECAUSE
// We call isGetValue(t, 'foo.bar.baz.say'), then we apply the lambda to the
// return value of isGetValue and 'hello'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment