|
1 | 1 | /* eslint-disable @typescript-eslint/no-unsafe-member-access */
|
2 | 2 | /* eslint-disable @typescript-eslint/no-explicit-any */
|
3 |
| -/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ |
4 |
| -/** |
5 |
| - * Memo class used for decycle json objects. Uses WeakSet if available otherwise array. |
6 |
| - */ |
7 |
| -export class Memo { |
8 |
| - /** Determines if WeakSet is available */ |
9 |
| - private readonly _hasWeakSet: boolean; |
10 |
| - /** Either WeakSet or Array */ |
11 |
| - private readonly _inner: any; |
12 | 3 |
|
13 |
| - public constructor() { |
14 |
| - this._hasWeakSet = typeof WeakSet === 'function'; |
15 |
| - this._inner = this._hasWeakSet ? new WeakSet() : []; |
16 |
| - } |
| 4 | +export type MemoFunc = [(obj: any) => boolean, (obj: any) => void]; |
17 | 5 |
|
18 |
| - /** |
19 |
| - * Sets obj to remember. |
20 |
| - * @param obj Object to remember |
21 |
| - */ |
22 |
| - public memoize(obj: any): boolean { |
23 |
| - if (this._hasWeakSet) { |
24 |
| - if (this._inner.has(obj)) { |
| 6 | +/** |
| 7 | + * Helper to decycle json objects |
| 8 | + */ |
| 9 | +export function memoBuilder(): MemoFunc { |
| 10 | + const hasWeakSet = typeof WeakSet === 'function'; |
| 11 | + const inner: any = hasWeakSet ? new WeakSet() : []; |
| 12 | + function memoize(obj: any): boolean { |
| 13 | + if (hasWeakSet) { |
| 14 | + if (inner.has(obj)) { |
25 | 15 | return true;
|
26 | 16 | }
|
27 |
| - this._inner.add(obj); |
| 17 | + inner.add(obj); |
28 | 18 | return false;
|
29 | 19 | }
|
30 | 20 | // eslint-disable-next-line @typescript-eslint/prefer-for-of
|
31 |
| - for (let i = 0; i < this._inner.length; i++) { |
32 |
| - const value = this._inner[i]; |
| 21 | + for (let i = 0; i < inner.length; i++) { |
| 22 | + const value = inner[i]; |
33 | 23 | if (value === obj) {
|
34 | 24 | return true;
|
35 | 25 | }
|
36 | 26 | }
|
37 |
| - this._inner.push(obj); |
| 27 | + inner.push(obj); |
38 | 28 | return false;
|
39 | 29 | }
|
40 | 30 |
|
41 |
| - /** |
42 |
| - * Removes object from internal storage. |
43 |
| - * @param obj Object to forget |
44 |
| - */ |
45 |
| - public unmemoize(obj: any): void { |
46 |
| - if (this._hasWeakSet) { |
47 |
| - this._inner.delete(obj); |
| 31 | + function unmemoize(obj: any): void { |
| 32 | + if (hasWeakSet) { |
| 33 | + inner.delete(obj); |
48 | 34 | } else {
|
49 |
| - for (let i = 0; i < this._inner.length; i++) { |
50 |
| - if (this._inner[i] === obj) { |
51 |
| - this._inner.splice(i, 1); |
| 35 | + for (let i = 0; i < inner.length; i++) { |
| 36 | + if (inner[i] === obj) { |
| 37 | + inner.splice(i, 1); |
52 | 38 | break;
|
53 | 39 | }
|
54 | 40 | }
|
55 | 41 | }
|
56 | 42 | }
|
| 43 | + return [memoize, unmemoize]; |
57 | 44 | }
|
0 commit comments