Run a Function Only Once
A once wrapper: the first call runs, every call after it does nothing.
JavaScript · ES6 — Pratik Rai ·
Fold an array of functions into one, applied right to left.
Write compose(functions) that folds the array into one function. Calling the result with a value feeds that value to the last function first, then passes each output leftwards to the function before it.
So compose([a, b, c])(v) means a(b(c(v))). With no functions at all, the result simply hands back whatever it was called with.
Input:
JSfile.javascript1const fn = compose([(x) => x * 10, (x) => x - 1]); 2fn(5);
Output:
40
The rightmost function runs first: 5 minus 1 is 4, and 4 times 10 is 40. Running them left to right would have given 49.
pipe, which many codebases prefer because it reads in execution order.compose([f, g, h])(x) is f(g(h(x))) — the last function in the array sees the input first. That ordering comes from mathematics, where f ∘ g means apply g then f.
It is a fold from the right, starting at the input value.
JSfile.javascript1function compose(functions) { 2 return (x) => functions.reduceRight((acc, fn) => fn(acc), x); 3}
The empty case falls out for free: with no functions, reduceRight returns the initial value, which is the input unchanged.
Reverse the direction and you have pipe, which many codebases prefer precisely because it reads in execution order. Knowing why both exist is usually the follow-up.
Goal: Return one function that applies the whole array right to left.
compose([f, g])(x) is f(g(x)).f ∘ g means apply g first. Reversing the direction gives pipe, which many codebases prefer because it reads in the order things happen.reduceRight with the input as the initial value gives that without a special case.applyMiddleware are built on it, as are most functional utility libraries. It also underpins how a chain of transformations is expressed without nesting calls twenty levels deep.Continue learning with these related challenges
A once wrapper: the first call runs, every call after it does nothing.
JavaScript · ES6 — Pratik Rai ·
Convert a Node-style (error, value) callback API into one that returns a promise.
JavaScript · ES6 — Pratik Rai ·
Cache a function by its arguments so the same call never computes twice.
JavaScript · ES6 — Pratik Rai ·
A once wrapper: the first call runs, every call after it does nothing.
JavaScript · ES6
Pratik Rai ·
Convert a Node-style (error, value) callback API into one that returns a promise.
JavaScript · ES6
Pratik Rai ·
Cache a function by its arguments so the same call never computes twice.
JavaScript · ES6
Pratik Rai ·