|
1 | 1 | import { isPlainObject } from './isPlainObject'; |
2 | 2 | import { pathToPointer } from './pathToPointer'; |
3 | 3 |
|
4 | | -export const decycle = (obj: unknown, replacer?: (value: any) => any) => { |
| 4 | +export function decycle(obj: unknown, replacer?: (value: any) => any) { |
5 | 5 | const objs = new WeakMap<object, string>(); |
6 | | - return (function derez(value: any, path: string[]) { |
7 | | - // The new object or array |
8 | | - let curObj: any; |
9 | | - |
10 | | - // If a replacer function was provided, then call it to get a replacement value. |
11 | | - if (replacer) value = replacer(value); |
| 6 | + const objectsToBeDeleted: object[] = []; // To keep track of objects to delete later |
12 | 7 |
|
| 8 | + function derez(value: any, path: (string | number)[]): any { |
| 9 | + if (replacer) { |
| 10 | + value = replacer(value); |
| 11 | + } |
13 | 12 | if (isPlainObject(value) || Array.isArray(value)) { |
14 | | - // The path of an earlier occurance of value |
15 | 13 | const oldPath = objs.get(value); |
| 14 | + |
16 | 15 | // If the value is an object or array, look to see if we have already |
17 | 16 | // encountered it. If so, return a {"$ref":PATH} object. |
18 | | - if (oldPath) return { $ref: oldPath }; |
19 | | - |
| 17 | + if (oldPath) { |
| 18 | + return { $ref: oldPath }; |
| 19 | + } |
20 | 20 | objs.set(value, pathToPointer(path)); |
21 | 21 | // If it is an array, replicate the array. |
22 | 22 | if (Array.isArray(value)) { |
23 | | - curObj = value.map((element, i) => derez(element, [...path, String(i)])); |
24 | | - } else { |
25 | | - // It is an object, replicate the object. |
26 | | - curObj = {}; |
27 | | - Object.keys(value).forEach(name => { |
28 | | - curObj[name] = derez(value[name], [...path, name]); |
29 | | - }); |
| 23 | + return value.map((element, i) => derez(element, [...path, i])); |
30 | 24 | } |
31 | | - objs.delete(value); |
32 | | - return curObj; |
| 25 | + const newObj: Record<string, any> = {}; |
| 26 | + for (const name in value) { |
| 27 | + if (Object.prototype.hasOwnProperty.call(value, name)) { |
| 28 | + newObj[name] = derez(value[name], [...path, name]); |
| 29 | + } |
| 30 | + } |
| 31 | + // Schedule object for deletion after derez completes |
| 32 | + objectsToBeDeleted.push(value); |
| 33 | + return newObj; |
33 | 34 | } |
34 | 35 | return value; |
35 | | - })(obj, []); |
36 | | -}; |
| 36 | + } |
| 37 | + |
| 38 | + const result = derez(obj, []); |
| 39 | + |
| 40 | + // Clean up objs for objects that were processed |
| 41 | + objectsToBeDeleted.forEach(obj => { |
| 42 | + objs.delete(obj); |
| 43 | + }); |
| 44 | + |
| 45 | + return result; |
| 46 | +} |
0 commit comments