-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchainOfResponsibility.js
More file actions
72 lines (60 loc) · 1.67 KB
/
chainOfResponsibility.js
File metadata and controls
72 lines (60 loc) · 1.67 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
/*
The Chain of Responsibility - pattern provides a chain of loosely coupled objects one of which can satisfy a request.
This pattern is essentially a linear search for an object that can handle a particular request.
*/
//=========================1)Build on prototypes========================//
const Text = function(s) {
this.value = s;
};
Text.prototype.line = function(a) {
this.value += '\n' + a;
return this;
};
Text.prototype.toString = function() {
return this.value;
};
// Usage
const txt = new Text('line1')
.line('line2')
.line('line3')
.line('line4');
//console.log(`${txt}`);
//=========================2)Functional chaining: Functor=======================//
{
const text = (s = '') => ({
line: (a) => text(`${s}\n${a}`),
toString: () => s
});
// Usage
//Each times creates new instance it's not fast!!!
const txt = text('line1')
.line('line2')
.line('line3')
.line('line4');
//console.log(`${txt}`);
}
//=========================3)Functional chaining: Functor - optimized=======================//
{
const text = (s = '', o = {
line: (a) => (s += '\n' + a, o),
toString: () => s
}) => o;
// Usage
//Each times we returning a refer on the object from closure.
const txt = text('line1')
.line('line2')
.line('line3')
.line('line4');
//console.log(`${txt}`);
}
//=========================4)Promises=======================//
{
const request = Promise.resolve('resolved');
request
.then(val => val + ' 1')
.then(val => val + ' 2')
.then(val => val + ' 3')
.then(val => console.log(val))
.finally(() => console.log('Promise finished!!!'))
.catch((err) => console.log('Error:', err));
}