Skip to content

Commit fa24856

Browse files
fix: Optimised code for performance (#142)
1 parent a9acf41 commit fa24856

File tree

1 file changed

+6
-7
lines changed

1 file changed

+6
-7
lines changed

src/decycle.ts

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,39 +3,38 @@ import { pathToPointer } from './pathToPointer';
33

44
export function decycle(obj: unknown, replacer?: (value: any) => any) {
55
const objs = new WeakMap<object, string>();
6+
const processedObjs = new WeakSet<object>();
67
function derez(value: any, path: (string | number)[]): any {
78
if (replacer) {
89
value = replacer(value);
910
}
10-
1111
if (isPlainObject(value) || Array.isArray(value)) {
1212
// The path of an earlier occurance of value
1313
const oldPath = objs.get(value);
14-
1514
// If the value is an object or array, look to see if we have already
1615
// encountered it. If so, return a {"$ref":PATH} object.
1716
if (oldPath) {
1817
return { $ref: oldPath };
1918
}
20-
2119
objs.set(value, pathToPointer(path));
2220
// If it is an array, replicate the array.
2321
if (Array.isArray(value)) {
2422
return value.map((element, i) => derez(element, [...path, i]));
2523
}
26-
2724
const newObj: Record<string, any> = {};
2825
for (const name in value) {
2926
if (Object.prototype.hasOwnProperty.call(value, name)) {
3027
newObj[name] = derez(value[name], [...path, name]);
3128
}
3229
}
33-
// deleteing object before returing
34-
objs.delete(value);
30+
// Only delete the object from the map if it has not been processed before
31+
if (!processedObjs.has(value)) {
32+
objs.delete(value);
33+
}
34+
processedObjs.add(value);
3535
return newObj;
3636
}
3737
return value;
3838
}
39-
4039
return derez(obj, []);
4140
}

0 commit comments

Comments
 (0)