-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy path7-chaining.js
More file actions
47 lines (36 loc) · 948 Bytes
/
7-chaining.js
File metadata and controls
47 lines (36 loc) · 948 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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
'use strict';
// Imperative: Mutable state, class-based, method chaining
class Adder {
constructor(initial) {
this.value = initial;
}
add(x) {
this.value += x;
return this;
}
valueOf() {
return this.value;
}
}
const sum1 = new Adder(1).add(9).add(1).add(7);
console.log('Sum:', +sum1);
// Functional: Immutable function composition
const adder = (initial) =>
Object.assign((value) => adder(initial + value), {
valueOf: () => initial,
map: (f) => f(initial),
toString: () => String(initial),
});
const sum2 = adder(1)(9)(1)(7);
console.log('Sum:', +sum2);
sum2.map(console.log);
// Enhanced functional methods with composition
const add = (initial) => ({
add: (value) => add(initial + value),
valueOf: () => initial,
map: (f) => f(initial),
toString: () => String(initial),
});
const sum3 = add(1).add(9).add(1).add(7);
console.log('Sum:', +sum3);
console.log('String:', String(sum3));