Last active
January 3, 2018 11:54
-
-
Save mattijs/15173a6b996a47b3ea73e834860652de to your computer and use it in GitHub Desktop.
Curry function (JavaScript)
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
// Adaptation of http://chriswarbo.net/blog/2012-10-01-better_currying_in_javascript.html | |
/** | |
* Make the inout function f curryable. | |
* | |
* @param {function} f | |
* @returns {function} | |
*/ | |
const curry = c = function(f) { | |
const apply = function(args) { | |
// Helper function. | |
// Takes an array of arguments args, returns | |
// f(args[0], args[1], ..., args[args.length - 1]) | |
var extra_args = args.slice(f.length); | |
var result = f.apply(null, args.slice(0, f.length)); | |
extra_args.forEach(function(a) { | |
result = result(a); | |
}); | |
return result; | |
}; | |
var add_args = function(old_args) { | |
// Helper function. | |
// Takes an array of arguments we've been given so far, | |
// If they're enough for f then we run it. | |
if (old_args.length >= f.length) return apply(old_args); | |
// If not, we return a function to gather more. | |
return function() { | |
var new_args = []; | |
for (var i = 0; i < arguments.length; i++) | |
new_args.push(arguments[i]); | |
return add_args(old_args.concat(new_args)); | |
}; | |
}; | |
// We kick things off by applying no arguments | |
return add_args([]); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment