-
-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy path2-compose.js
More file actions
25 lines (23 loc) · 636 Bytes
/
2-compose.js
File metadata and controls
25 lines (23 loc) · 636 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
'use strict';
const compose = (...fns) => {
const events = new Map();
const outputFn = x =>
fns.reduceRight((arg, fn, i, arr) => {
try {
return fn(arg);
} catch (e) {
arr.length = 0;
return outputFn.emit('error', e);
}
}, x);
outputFn.emit = (event, ...args) => {
const handlers = events.get(event);
if (handlers) handlers.forEach(fn => fn(...args));
};
outputFn.on = (event, handler) => {
const existsEvent = events.get(event);
existsEvent ? existsEvent.push(handler) : events.set(event, [handler]);
};
return outputFn;
};
module.exports = { compose };