Last active
December 2, 2021 05:45
-
-
Save ewilliams-zoot/c944aa8bc1f5c474128eb67c736e7983 to your computer and use it in GitHub Desktop.
Functional Programming Notes
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
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 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
/** | |
* 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