Created
June 19, 2015 21:41
-
-
Save gordonbrander/1b2f96657eb6d47f14ed to your computer and use it in GitHub Desktop.
comp.js
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
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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Forget method chaining with this one weird tip!