-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path1-theory.js
More file actions
73 lines (62 loc) · 1.43 KB
/
1-theory.js
File metadata and controls
73 lines (62 loc) · 1.43 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
61
62
63
64
65
66
67
68
69
70
71
72
73
'use strict';
class AbstractHandler {
constructor() {
const proto = Object.getPrototypeOf(this);
if (proto.constructor === AbstractHandler) {
throw new Error('Abstract class should not be instanciated');
}
this.next = null;
}
method(value) {
const s = JSON.stringify({ method1: { value } });
throw new Error('Method is not implemented: ' + s);
}
}
class NumberHandler extends AbstractHandler {
method(value, next) {
if (typeof value === 'number') {
return value.toString();
}
return next();
}
}
class ArrayHandler extends AbstractHandler {
method(value, next) {
if (Array.isArray(value)) {
return value.reduce((a, b) => a + b);
}
return next();
}
}
class Sender {
constructor() {
this.first = null;
this.last = null;
}
add(handler) {
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.method(value, () => {
current = current.next;
if (current) return step();
throw new Error('No handler detected');
});
return step().toString();
}
}
// Usage
const sender = new Sender().add(new NumberHandler()).add(new ArrayHandler());
{
const result = sender.process(100);
console.dir({ result });
}
{
const result = sender.process([1, 2, 3]);
console.dir({ result });
}