Skip to content

Instantly share code, notes, and snippets.

@nelix
Forked from amatiasq/curry.js
Last active November 13, 2015 16:56
Show Gist options
  • Save nelix/5eaf5cbab2f478974aff to your computer and use it in GitHub Desktop.
Save nelix/5eaf5cbab2f478974aff to your computer and use it in GitHub Desktop.
Simple way to recursively curry javascript functions http://jsfiddle.net/amatiasq/osrsomq0/
/**
* @param {Function} fn Function to curry.
* @param {Number} lenght of the arguments required to invoke the function.
* @returns {Function} The currified function.
*/
const curry = (fn, length = fn.length) => function currified(...args) {
if (args.length === 0) {
return currified;
}
if (args.length >= length)
return fn.apply(this, args);
}
const child = fn.bind.apply(fn, [this, ...args]);
return curry(child, length - args.length);
};
var log = console.log.bind(console);
// empty calls are ignored
curry(log, 1) ()()()()(1); // Logs: 1
// extra args are passed
curry(log, 1) (1, 2, 3, 4); // Logs: 1 2 3 4
// recursive currification
curry(log, 5) (1)(2)(3)(4)(5); // 1 2 3 4 5
// works with all combination
curry(log, 4) (1, 2, 3, 4); // Logs: 1 2 3 4
curry(log, 4) (1, 2, 3)(4); // Logs: 1 2 3 4
curry(log, 4) (1, 2)(3, 4); // Logs: 1 2 3 4
curry(log, 4) (1)(2, 3, 4); // Logs: 1 2 3 4
curry(log, 4) (1, 2)(3)(4); // Logs: 1 2 3 4
curry(log, 4) (1)(2)(3, 4); // Logs: 1 2 3 4
curry(log, 4) (1)(2, 3)(4); // Logs: 1 2 3 4
curry(log, 4) (1)(2)(3)(4); // Logs: 1 2 3 4
// function is not invoked until argument lenght is reached
console.log(curry(log, 4) (1)(2)(3)); // returns function currified() { ... }
// when argument length is reached function is invoked and its result is returned
try {
curry(log, 4) (1)(2)(3)(4)(5); // logs 1 2 3 4 & throws undefined is not a function
} catch(err) {
console.log(err);
}
function sum(a, b) {
return a + b;
}
// argument length detected automatically
console.log(curry(sum)(1)(2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment