Implement a `createChain()` with `addHandler(fn)` and `handle(request)`. Each handler can process the request or pass to the next.
Problem Statement
Implement a `createChain()` with `addHandler(fn)` and `handle(request)`. Each handler can process the request or pass to the next.
Complexity
Time Complexity: -
Space Complexity: -
Hints
š” Hint 1:
Chain of Responsibility passes a request through a chain of handlers.
š” Hint 2:
Each handler decides to process or pass to next.
š” Hint 3:
Handlers call next() to pass to the next handler in the chain.
ā
Solution:
```javascript
function createChain() {
const handlers = [];
return {
addHandler(fn) { handlers.push(fn); },
handle(request) {
let index = 0;
function next() {
if (index < handlers.length) {
handlers[index++](request, next);
}
}
next();
return request;
}
};
}
```