-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
immutable.js
49 lines (43 loc) · 1.03 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
/* global Record Tuple */
export function deepFreeze(thing) {
switch(typeof thing) {
case 'function':
throw new TypeError('Functions cannot be made immutable.');
case 'object':
if (thing === null) {
return null;
} else if (Array.isArray(thing)) {
return Object.freeze(thing.map(deepFreeze));
} else {
return Object.freeze(
Object.fromEntries(
Object.entries(thing)
.map(([key, val]) => [key, deepFreeze(val)])
)
);
}
default:
return thing;
}
}
export function getImmutable(thing) {
switch(typeof thing) {
case 'function':
throw new TypeError('Functions cannot be made immutable.');
case 'object':
if (thing === null) {
return null;
} else if (thing instanceof Record || thing instanceof Tuple) {
return thing;
} else if (Array.isArray(thing)) {
return Tuple.from(thing.map(getImmutable));
} else {
return Record.fromEntries(
Object.entries(thing)
.map(([key, val]) => [key, getImmutable(val)])
);
}
default:
return thing;
}
}