-
-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy path2-compose.js
More file actions
31 lines (27 loc) · 671 Bytes
/
2-compose.js
File metadata and controls
31 lines (27 loc) · 671 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
'use strict';
const compose = (...fns) => {
const eventHandlers = {};
const composedFn = (x) => {
if (fns.length === 0) return x;
let result = x;
try {
for (let i = fns.length - 1; i >= 0; i--) {
result = fns[i](result);
}
} catch (error) {
if (eventHandlers.error) {
eventHandlers.error.forEach(handler => handler(error));
}
return undefined;
}
return result;
};
composedFn.on = (eventType, handler) => {
if (!eventHandlers[eventType]) {
eventHandlers[eventType] = [];
}
eventHandlers[eventType].push(handler);
};
return composedFn;
};
module.exports = { compose };