Created
October 10, 2015 00:58
-
-
Save RSNara/2be5562a3492be945cc4 to your computer and use it in GitHub Desktop.
Currying but with an options object!
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
var curry = (function() { | |
return curry; | |
function isObject(thing) { | |
return Object(thing) === thing; | |
} | |
function isEmpty(object) { | |
return isObject(object) && ! Object.keys(object).length; | |
} | |
function satisfies(contract, object) { | |
return Object.keys(contract) | |
.reduce(function(yes, key){ | |
var wrapped = Object(object); | |
return yes | |
&& wrapped.hasOwnProperty(key) | |
&& (isObject(contract[key]) | |
? satisfies(contract[key], wrapped[key]) | |
: true); | |
}, true); | |
} | |
function clone(object) { | |
return isEmpty(object) ? {} : merge({}, object); | |
} | |
function merge(target, options) { | |
return Object.keys(options) | |
.reduce(function(copy, key){ | |
copy[key] = isObject(options[key]) | |
? merge({}, options[key]) | |
: options[key]; | |
return copy; | |
}, clone(target)); | |
} | |
function curry(fn, contract) { | |
return function func(options) { | |
if (! satisfies(contract, options)) { | |
return function inner(innerOptions){ | |
return func.call(this, merge(options, innerOptions)); | |
}; | |
} else { | |
return fn.call(this, options); | |
} | |
} | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment