Exercise 5: Pipe (left-to-right)
Problem Statement
Create a function pipe(...fns) that applies value left-to-right.
Sample Output:
pipe((x) => x * 2, (x) => x + 5, (x) => x * 3)(10) => 75 // Steps: 10*2=20, 20+5=25, 25*3=75
Solution
const pipe = (...fns) => (x) => fns.reduce((v, f) => f(v), x);Explanation
Overall Goal:
- Multiple functions ko left-to-right sequence me apply karna.
- Data transformation pipeline banana.
Single Line Solution:
const pipe = (...fns) => (x) => fns.reduce((v, f) => f(v), x);
Part 1: Function header
const pipe = (...fns) =>...fns→ rest parameter: koi bhi number of functions accept karega.- Example:
pipe(a, b, c)→fns = [a, b, c].
Part 2: Return function
(x) =>→ function return karta hai jo initial value lega.
Part 3: Reduce logic
fns.reduce((v, f) => f(v), x)reduce→ array ko traverse karke single value produce karta hai.(v, f) => f(v)→ reducer function:v→ accumulator (current value after transformations).f→ current function from array.f(v)→ function ko current value pe apply karo.x→ initial value (starting point).
How it works:
pipe(double, add5, square)(10)- Step 1:
double(10)→20(v = 20). - Step 2:
add5(20)→25(v = 25). - Step 3:
square(25)→625(final result).
Real world:
- Data processing: clean → transform → format.
- Functional programming: compose multiple operations.
- Lodash/fp libraries me similar pattern use hota hai.