From 210976364c03912aa668eeb51b2eebda686c5079 Mon Sep 17 00:00:00 2001 From: atomiks Date: Fri, 15 Dec 2017 09:04:08 +1100 Subject: [PATCH] Create compose-functions.md --- snippets/compose-functions.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 snippets/compose-functions.md diff --git a/snippets/compose-functions.md b/snippets/compose-functions.md new file mode 100644 index 000000000..cd60bb7e0 --- /dev/null +++ b/snippets/compose-functions.md @@ -0,0 +1,15 @@ +### Compose functions + +Use the `...rest` operator to gather all function arguments into an array. Return a function which takes +a single argument and uses `Array.reduceRight()` to return the result of applying each function. + +```js +const compose = (...fns) => n => fns.reduceRight((acc, fn) => fn(acc), n); +/* +const addOne = n => n + 1; +const square = n => n * n; +const double = n => n * 2; +compose(addOne, square, double)(2) -> 17 +equivalent to: addOne(square(double(2))) +*/ +```