forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
immutability-helper.ts
36 lines (32 loc) · 918 Bytes
/
immutability-helper.ts
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
// Time: O(1)
// Space: O(1)
// proxy
type InputObj = Record<any, any> | Array<any>;
var makeMutations = (obj, lookup) => {
return new Proxy(obj, {
set(_, prop, value) {
lookup[prop] = value;
return true;
},
get(target, prop) {
if (typeof obj[prop] === 'object' && obj[prop] !== null) {
if (lookup[prop] === undefined) {
lookup[prop] = {};
}
return makeMutations(obj[prop], lookup[prop]);
}
return lookup[prop] !== undefined ? lookup[prop] : Reflect.get(target, prop);
}
});
};
class ImmutableHelper {
#obj: InputObj;
constructor(obj: InputObj) {
this.#obj = obj;
}
produce(mutator: (obj: InputObj) => void) {
var lookup = {};
mutator(makeMutations(this.#obj, lookup));
return lookup;
}
}