-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path5-stateless.js
More file actions
75 lines (62 loc) · 1.5 KB
/
5-stateless.js
File metadata and controls
75 lines (62 loc) · 1.5 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
74
75
'use strict';
class Future {
#executor;
constructor(executor) {
this.#executor = executor;
}
static of(value) {
return new Future((resolve) => resolve(value));
}
chain(fn) {
return new Future((resolve, reject) =>
this.fork(
(value) => fn(value).fork(resolve, reject),
(error) => reject(error),
),
);
}
map(fn) {
return this.chain((value) => Future.of(fn(value)));
}
fork(successed, failed) {
this.#executor(successed, failed);
}
}
// Usage
const f1 = Future.of(6);
const f2 = f1.map((x) => ++x);
const f3 = f2.map((x) => x ** 3);
const f4 = f1.map((x) => x * 2);
/*
F(6)
|
f1---\
| |
f2 f4
|
f3
*/
f1.fork((x) => console.log('f1 fork1', x));
f1.fork((x) => console.log('f1 fork2', x));
f2.fork((x) => console.log('f2 fork1', x));
f2.fork((x) => console.log('f2 fork2', x));
f3.fork((x) => console.log('f3 fork1', x));
f3.fork((x) => console.log('f3 fork2', x));
f4.fork((x) => console.log('f4 fork1', x));
f4.fork((x) => console.log('f4 fork2', x));
console.log('\nChange initial value of chain:');
{
const source = (r) => r(source.value);
source.value = 2;
const f1 = new Future(source)
.map((x) => ++x)
.map((x) => x ** 3)
.map((x) => x * 2);
f1.fork((x) => console.log('fork1', x));
source.value = 3;
f1.fork((x) => console.log('fork2', x));
source.value = 4;
f1.fork((x) => console.log('fork3', x));
source.value = 5;
f1.fork((x) => console.log('fork4', x));
}