Skip to content

Instantly share code, notes, and snippets.

@ewilliams-zoot
Last active December 2, 2021 05:45
Show Gist options
  • Save ewilliams-zoot/c944aa8bc1f5c474128eb67c736e7983 to your computer and use it in GitHub Desktop.
Save ewilliams-zoot/c944aa8bc1f5c474128eb67c736e7983 to your computer and use it in GitHub Desktop.
Functional Programming Notes
const compose = (...fns) => (...args) => fns.reduceRight((acc, fn) => [fn(...acc)], args)[0];
// sub :: (a, b) -> a
const sub = curry((a, b) => b - a);
const mathPipeline = compose(increment, sub(2), add(4));
mathPipeline(10);// 13
/**
* This programmatically breaks a function from this
* (a, b, c) => doSomething
* to this:
* (a) => (b) => (c) => doSomething || (a, b) => (c) => doSomething
* This is one reason why JS is quite a functional language and very reflective
* @param {Function} fn - A function with two or more parameters that you want broken down into a curry
*/
const curry = (fn) => {
const arity = fn.length;
return function $curry(...args) {
if (args.length < arity) {
return $curry.bind(null, ...args);
}
return fn.apply(null, args);
};
};
const add = curry((a, b) => a + b);
const increment = add(1);
increment(10);// 11
const filter = curry((fn, items) => items.filter(fn));
const noLetterAFilter = filter((item) => !/a/ig.test(item));
noLetterAFilter(["hello", "world", "apple"]);// ["hello", "world"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment