-
Notifications
You must be signed in to change notification settings - Fork 0
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.
Imagine the pipe function as a factory assembly line for your data: it starts at one end and then gets worked on step by step, with each function in the pipe being a station where your data gets tweaked and refined. It's really useful when you want to process something in a sequential manner.
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