Implement a `createPipeline()` that has `use(fn)` and `execute(context)`. Each middleware calls `next()` to pass to the next one. Returns the final context.
Problem Statement
Implement a `createPipeline()` that has `use(fn)` and `execute(context)`. Each middleware calls `next()` to pass to the next one. Returns the final context.
Complexity
Time Complexity: -
Space Complexity: -
Hints
š” Hint 1:
Middleware functions have signature: (context, next) => { ... }.
š” Hint 2:
Compose middleware by chaining next() calls.
š” Hint 3:
Iterate through middleware in order, each calling the next.
ā
Solution:
```javascript
function createPipeline() {
const middlewares = [];
return {
use(fn) { middlewares.push(fn); },
execute(context) {
let index = 0;
function next() {
if (index < middlewares.length) {
middlewares[index++](context, next);
}
}
next();
return context;
}
};
}
```