Skip to content

Instantly share code, notes, and snippets.

@YannickLeRoux
Created March 13, 2020 16:57
Show Gist options
  • Save YannickLeRoux/4c049d12c18c9cfcdb96fd3d6438f3ff to your computer and use it in GitHub Desktop.
Save YannickLeRoux/4c049d12c18c9cfcdb96fd3d6438f3ff to your computer and use it in GitHub Desktop.
Useful utilities to manipulate functions
/**
* 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