Last active
December 13, 2015 17:38
-
-
Save bigs/4949010 to your computer and use it in GitHub Desktop.
A cute currying function written in pure JavaScript for FUNZIES.
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 (f, args, binding) { | |
if (typeof f !== 'function' || | |
toString.call(args) !== '[object Array]') { | |
throw new Error('Invalid parameters'); | |
return; | |
} | |
if (typeof binding !== 'object') { | |
binding = this; | |
} | |
return function () { | |
var _args = args.concat(Array.prototype.slice.call(arguments)); | |
return f.apply(binding, _args); | |
}; | |
}; | |
// Example usage | |
var add = function(x, y, z) { | |
return x + y + z; | |
}; | |
var addTwo = curry(add, [2]); | |
console.log(addTwo(4, 6)); // 12 | |
console.log(addTwo(1, 3)); // 6 | |
var addTwoAndFour = curry(add, [2, 4]); | |
console.log(addTwoAndFour(6)); // 12 as well! |
I was brainstorming how to refine my own curry function when someone mentioned Function.prototype.bind...
function curry(f, args){
return f.length > 1 ? function(){
var params = args ? args.concat() : [];
return params.push.apply(params, arguments) < f.length && arguments.length ?
curry.call(this, f, params) : f.apply(this, params);
} : f;
}
var add = curry(function(x,y){
return x + y;
});
var addTwo = add(2);
console.log(addTwo(3));
> Function.prototype.betterBind = function (scope, arg1) {
var args = Array.prototype.slice.call(arguments, 1);
var func = this;
return function () {
return Function.prototype.apply.call(
func,
scope === null ? this : scope,
args.concat(Array.prototype.slice.call(arguments)));
};
};
Function.prototype.curry = Function.prototype.betterBind.betterBind(null, null);
> (function (x,y) { return x + y }).curry(1).curry(2)()
3
> (function (x,y) { return x + y }).curry(1,2)()
3
awesome feedback/code, guys! always amazed by the number of unique solutions to problems in js.
@wyattanderson i don't think that is universally supported? if so, could have saved some time!
@alb i discovered that shortly after the brief exercise — it often times works out that way.. thanks for the link.
@pabloPXL read that one over a few times — nifty implementation.
@bergmark lovely, thanks.
made a final edit with some of your suggestions/hints
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Array.isArray