Created
March 13, 2020 16:57
-
-
Save YannickLeRoux/4c049d12c18c9cfcdb96fd3d6438f3ff to your computer and use it in GitHub Desktop.
Useful utilities to manipulate functions
This file contains hidden or 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
/** | |
* Composes a function that returns the result of invoking the given functions | |
* with the `this` binding of the created function, where each successive | |
* invocation is supplied the return value of the previous. | |
**/ | |
export function pipe(...funcs) { | |
const length = funcs.length; | |
let index = length; | |
while (index--) { | |
if (typeof funcs[index] !== 'function') { | |
throw new TypeError('Expected a function'); | |
} | |
} | |
return function(...args) { | |
let index = 0; | |
let result = length ? funcs[index].apply(this, args) : args[0]; | |
while (++index < length) { | |
result = funcs[index].call(this, result); | |
} | |
return result; | |
}; | |
} | |
export function compose(...funcs) { | |
return pipe(...funcs.reverse()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment