How to implement pipe function
Daisho Komiyama edited this page Nov 4, 2023
·
2 revisions
The pipe function takes a list of functions and combines them into a single function that runs your data through each function in turn. It's like an assembly line for your code: you put a value in one end, and it comes out the other end transformed by each function in the sequence.
const pipe = (...fns) => value => {
return fns.reduce((value, fn) => {
return fn(value)
}, value);
}
const add10 = n => {
return n + 10;
}
const devideBy2 = n => {
return n / 2;
}
// usage
const processNumbers = pipe(add10, devideBy2)
console.log(processNumbers(2)) // 6