Skip to content

Instantly share code, notes, and snippets.

@yukeehan
Created October 30, 2018 13:49
Show Gist options
  • Save yukeehan/472f45797635d5de9e782ad2a9e2a2e4 to your computer and use it in GitHub Desktop.
Save yukeehan/472f45797635d5de9e782ad2a9e2a2e4 to your computer and use it in GitHub Desktop.
.pipe( ) function in JS
// pipe function: A pipe function takes an n sequence of operations; in which each operation takes an argument;
// process it; and gives the processed output as an input for the next operation in the sequence. The result of a
// pipe function is a function that is a bundled up version of the sequence of operations.
//======= two functions in pipe function =========
const pipe = (op1, op2) => {
return (arg) => {
const result1 = op1(arg);
return op2(result1);
}
}
// ======= refactor the pipe function ============
const pipe = (op1, op2) => (arg) => op2(op1(arg));
// ========== more functions in pipe func ===========
// Utilize the previous pipe function that accepts only two functions
const _pipe = (a, b) => (arg) => b(a(arg));
// The rest parameters creates an array of operations
const pipe = (...ops) => {
// Iterate over the array of operations
// By using reduce, merge all operations into a single bundle
let bundle = ops.reduce((prevOp, nextOp) => {
return _pipe(prevOp,nextOp);
});
return bundle;
}
// ========== refactor one =================
const _pipe = (a, b) => (arg) => b(a(arg));
// Refactored
const pipe = (...ops) => ops.reduce(_pipe)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment