-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathmemo.ts
52 lines (49 loc) · 1.24 KB
/
memo.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/no-explicit-any */
export type MemoFunc = [
// memoize
(obj: any) => boolean,
// unmemoize
(obj: any) => void,
];
/**
* Helper to decycle json objects
*
* @deprecated This function is deprecated and will be removed in the next major version.
*/
// TODO(v9): Move this function into normalize() directly
export function memoBuilder(): MemoFunc {
const hasWeakSet = typeof WeakSet === 'function';
const inner: any = hasWeakSet ? new WeakSet() : [];
function memoize(obj: any): boolean {
if (hasWeakSet) {
if (inner.has(obj)) {
return true;
}
inner.add(obj);
return false;
}
// eslint-disable-next-line @typescript-eslint/prefer-for-of
for (let i = 0; i < inner.length; i++) {
const value = inner[i];
if (value === obj) {
return true;
}
}
inner.push(obj);
return false;
}
function unmemoize(obj: any): void {
if (hasWeakSet) {
inner.delete(obj);
} else {
for (let i = 0; i < inner.length; i++) {
if (inner[i] === obj) {
inner.splice(i, 1);
break;
}
}
}
}
return [memoize, unmemoize];
}