Created
July 4, 2013 19:24
-
-
Save imbcmdth/5929762 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
var not = function(fn){ return function(){ return !fn.apply(this, arguments); }; }; | |
var nullOrUndefined = function(e){ return this[e] == null; }; | |
var notNullOrUndefined = not(nullOrUndefined); | |
var existsIn = function(e){ return this.indexOf(e) != -1; }; | |
var doesntExistIn = not(existsIn); | |
var merge = function(dest, source){ | |
var validKeys = Object.keys(source).filter(notNullOrUndefined, source); | |
validKeys.forEach(function(e){ | |
dest[e] = source[e]; | |
}); | |
return dest; | |
}; | |
var genSauce = function(fn, existingArgs, argsRemaining){ | |
return function(args){ | |
var argsGiven = Object.keys(args).filter(notNullOrUndefined, args), | |
nextArgsRemaining = argsRemaining.filter(doesntExistIn, argsGiven); | |
existingArgs = merge(existingArgs, args); | |
if ( nextArgsRemaining.length === 0 ) return fn.call(this, existingArgs); | |
return genSauce(fn, existingArgs, nextArgsRemaining); | |
}; | |
}; | |
var masala = function(fn, args){ | |
var argsRemaining = Object.keys(args).filter(nullOrUndefined, args), | |
defaultArgs = merge({}, args); | |
return genSauce(fn, defaultArgs, argsRemaining); | |
}; | |
module.exports = masala; | |
/* Use: | |
function add(options) { | |
options.done(options.a + options.b); | |
} | |
var addSauce = masala(add, { done:null, a:null, b:null }); | |
var addAndLog = addSauce({ done: console.log.bind(console, "answer:") }); | |
var add2AndLog = addAndLog({ a: 2 }); | |
add2AndLog({b:3}); //=> "answer: 5" | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment