Skip to content

Commit

Permalink
fix: Optimised code for performance (#142)
Browse files Browse the repository at this point in the history
  • Loading branch information
SB-rohitdesai authored Jul 31, 2024
1 parent a9acf41 commit fa24856
Showing 1 changed file with 6 additions and 7 deletions.
13 changes: 6 additions & 7 deletions src/decycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,39 +3,38 @@ import { pathToPointer } from './pathToPointer';

export function decycle(obj: unknown, replacer?: (value: any) => any) {
const objs = new WeakMap<object, string>();
const processedObjs = new WeakSet<object>();
function derez(value: any, path: (string | number)[]): any {
if (replacer) {
value = replacer(value);
}

if (isPlainObject(value) || Array.isArray(value)) {
// The path of an earlier occurance of value
const oldPath = objs.get(value);

// If the value is an object or array, look to see if we have already
// encountered it. If so, return a {"$ref":PATH} object.
if (oldPath) {
return { $ref: oldPath };
}

objs.set(value, pathToPointer(path));
// If it is an array, replicate the array.
if (Array.isArray(value)) {
return value.map((element, i) => derez(element, [...path, i]));
}

const newObj: Record<string, any> = {};
for (const name in value) {
if (Object.prototype.hasOwnProperty.call(value, name)) {
newObj[name] = derez(value[name], [...path, name]);
}
}
// deleteing object before returing
objs.delete(value);
// Only delete the object from the map if it has not been processed before
if (!processedObjs.has(value)) {
objs.delete(value);
}
processedObjs.add(value);
return newObj;
}
return value;
}

return derez(obj, []);
}

0 comments on commit fa24856

Please sign in to comment.