forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
make-object-immutable.ts
31 lines (28 loc) · 978 Bytes
/
make-object-immutable.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
// Time: O(1)
// Space: O(1)
// proxy
type Obj = Array<any> | Record<any, any>;
const forbiddenMethods = new Set(["pop", "push", "shift", "unshift", "splice", "sort", "reverse"]);
function makeImmutable(obj: Obj): Obj {
return new Proxy(obj, {
set(target, prop) {
if (Array.isArray(target) && typeof prop === "string") {
if (Number(prop) !== undefined) {
throw `Error Modifying Index: ${prop}`;
}
}
throw `Error Modifying: ${prop.toString()}`;
},
get(target, prop) {
if (typeof obj[prop] === 'object' && obj[prop] !== null) {
return makeImmutable(obj[prop]);
}
if (forbiddenMethods.has(prop.toString())) {
return () => {
throw `Error Calling Method: ${prop.toString()}`;
}
}
return Reflect.get(target, prop);
}
});
};