Skip to content

Instantly share code, notes, and snippets.

@gordonbrander
Created June 19, 2015 21:41
Show Gist options
  • Select an option

  • Save gordonbrander/1b2f96657eb6d47f14ed to your computer and use it in GitHub Desktop.

Select an option

Save gordonbrander/1b2f96657eb6d47f14ed to your computer and use it in GitHub Desktop.
comp.js
const reduce = Array.reduce;
// Call function `f` with value `x`.
const callWith = (x, f) => f(x);
// Pipe value `x` through many single-argument functions in succession.
// This is kind of like a Unix pipe. The value of the previous function is
// passed to the next function, etc. Note that functions are called
// from left-to-right, with left being first.
export const pipe = (x, ...f) => reduce(f, callWith, x);
// Combine a list of one-argument functions into a single one-argument function
// that will pipe `x` through each function.
// This is like the classic `compose` function, but goes from left-to-right
// instead of right-to-left.
// Returns a function.
export const chain = (...f) => (x) => pipe(x, ...f);
// Compose 2 functions.
const comp2 = (z, y) => (x) => z(y(x));
// Classic RTL function composition.
export const comp = (f, ...fn) => reduce(fn, comp2, f);
@gordonbrander
Copy link
Copy Markdown
Author

Forget method chaining with this one weird tip!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment