Skip to content

Commit a8a81f7

Browse files
Fix/stop 184/performance issue (#143)
* fix: Optimised code for performance * fix: changes in logic for resolve test case issue
1 parent fa24856 commit a8a81f7

File tree

1 file changed

+21
-20
lines changed

1 file changed

+21
-20
lines changed

src/decycle.ts

Lines changed: 21 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,41 @@
11
import { isPlainObject } from './isPlainObject';
22
import { pathToPointer } from './pathToPointer';
33

4-
export function decycle(obj: unknown, replacer?: (value: any) => any) {
4+
export const decycle = (obj: unknown, replacer?: (value: any) => any) => {
55
const objs = new WeakMap<object, string>();
66
const processedObjs = new WeakSet<object>();
7-
function derez(value: any, path: (string | number)[]): any {
8-
if (replacer) {
9-
value = replacer(value);
10-
}
7+
8+
return (function derez(value: any, path: string[]) {
9+
// The new object or array
10+
let curObj: any;
11+
12+
// If a replacer function was provided, then call it to get a replacement value.
13+
if (replacer) value = replacer(value);
14+
1115
if (isPlainObject(value) || Array.isArray(value)) {
1216
// The path of an earlier occurance of value
1317
const oldPath = objs.get(value);
1418
// If the value is an object or array, look to see if we have already
1519
// encountered it. If so, return a {"$ref":PATH} object.
16-
if (oldPath) {
17-
return { $ref: oldPath };
18-
}
20+
if (oldPath) return { $ref: oldPath };
21+
1922
objs.set(value, pathToPointer(path));
2023
// If it is an array, replicate the array.
2124
if (Array.isArray(value)) {
22-
return value.map((element, i) => derez(element, [...path, i]));
23-
}
24-
const newObj: Record<string, any> = {};
25-
for (const name in value) {
26-
if (Object.prototype.hasOwnProperty.call(value, name)) {
27-
newObj[name] = derez(value[name], [...path, name]);
28-
}
25+
curObj = value.map((element, i) => derez(element, [...path, String(i)]));
26+
} else {
27+
// It is an object, replicate the object.
28+
curObj = {};
29+
Object.keys(value).forEach(name => {
30+
curObj[name] = derez(value[name], [...path, name]);
31+
});
2932
}
30-
// Only delete the object from the map if it has not been processed before
3133
if (!processedObjs.has(value)) {
3234
objs.delete(value);
3335
}
3436
processedObjs.add(value);
35-
return newObj;
37+
return curObj;
3638
}
3739
return value;
38-
}
39-
return derez(obj, []);
40-
}
40+
})(obj, []);
41+
};

0 commit comments

Comments
 (0)