-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimmutable.js
61 lines (47 loc) · 1.14 KB
/
immutable.js
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
// Immutable data
// Mutable can be changed after creation
// Immutable cannot be changed after creation
const a = [1, 2, 3];
const b = a;
b.push(4);
console.log(a);
const c = { foo: 'bar' };
const d = c;
d.foo = 'baz';
console.log(c.foo);
const push = value => array => {
const clone = [...array];
clone.push(value);
return clone;
};
const e = [1, 2, 3];
const f = push(4)(e);
console.log({ e, f });
class MutableGlass {
constructor(content, amount) {
this.content = content;
this.amount = amount;
}
takeDrink(value) {
this.amount = Math.max(this.amount - value, 0);
return this;
}
}
const mg1 = new MutableGlass('water', 100);
const mg2 = mg1.takeDrink(20);
console.log(mg1 === mg2);
console.log(mg1.amount === mg2.amount);
class ImmutableGlass {
constructor(content, amount) {
this.content = content;
this.amount = amount;
}
takeDrink(value) {
return new ImmutableGlass(this.content, Math.max(this.amount - value, 0));
}
}
const ig1 = new ImmutableGlass('water', 100);
const ig2 = ig1.takeDrink(20);
console.log(ig1 === ig2);
console.log(ig1.amount === ig2.amount);
console.log(ig1.amount, ig2.amount);