-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path2-simple.js
More file actions
60 lines (52 loc) · 1.04 KB
/
2-simple.js
File metadata and controls
60 lines (52 loc) · 1.04 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
'use strict';
class Handler {
constructor(fn) {
this.fn = fn;
this.next = null;
}
}
class Sender {
constructor() {
this.first = null;
this.last = null;
}
add(fn) {
const handler = new Handler(fn);
if (!this.first) this.first = handler;
else this.last.next = handler;
this.last = handler;
return this;
}
process(value) {
let current = this.first;
const step = () =>
current.fn(value, () => {
current = current.next;
if (current) return step();
throw new Error('No handler detected');
});
return step().toString();
}
}
// Usage
const sender = new Sender()
.add((value, next) => {
if (typeof value === 'number') {
return value.toString();
}
return next();
})
.add((value, next) => {
if (Array.isArray(value)) {
return value.reduce((a, b) => a + b);
}
return next();
});
{
const result = sender.process(100);
console.dir({ result });
}
{
const result = sender.process([1, 2, 3]);
console.dir({ result });
}