Skip to content

Instantly share code, notes, and snippets.

@aneurysmjs
Created April 18, 2019 08:52
Show Gist options
  • Save aneurysmjs/b6d6e6c4aa002bbbe550637135f59092 to your computer and use it in GitHub Desktop.
Save aneurysmjs/b6d6e6c4aa002bbbe550637135f59092 to your computer and use it in GitHub Desktop.
as
// Partial application and currying are two different techniques for specializing a generalized function
// Partial application takes some of the arguments now and then takes all of the rest arguments later
function partial(fn, ...firstArgs) {
return function applied(...lastArgs) {
return fn(...firstArgs, ...lastArgs);
};
}
// generalized function
const mult = (x, y) => x * y;
// specialized function
const multBy10 = partial(mult, 10);
multBy10(5); // 50
/**
* currying takes one argument at time
*/
function curry(fn, arity = fn.length ) {
return (function nextCurried(prevArgs) {
return function curried(nextArg) {
const args = [...prevArgs, nextArg];
if (args.length >= arity) {
return fn(...args);
} else {
return nextCurried(args);
}
};
}([]));
}
const makePoint = (x, y, z) => ({ x, y, z });
const curriedPoint = curry(makePoint);
const x = curriedPoint(1);
const y = x(2);
const z = y(5);
curriedPoint(1)(2)(5);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment