Skip to content

Commit

Permalink
Fix cyclical references
Browse files Browse the repository at this point in the history
  • Loading branch information
AsyncBanana committed Nov 8, 2021
1 parent 75c163f commit 3b6ab8f
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
8 changes: 5 additions & 3 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ const t = true;
const richTypes = { Date: t, RegExp: t, String: t, Number: t };
export default function diff(
obj: Record<string, any> | any[],
newObj: Record<string, any> | any[]
newObj: Record<string, any> | any[],
stack: Record<string, any>[] = []
): Difference[] {
let diffs: Difference[] = [];
for (const key in obj) {
Expand All @@ -21,9 +22,10 @@ export default function diff(
newObj[key] &&
typeof obj[key] === "object" &&
typeof newObj[key] === "object" &&
!richTypes[Object.getPrototypeOf(obj[key]).constructor.name]
!richTypes[Object.getPrototypeOf(obj[key]).constructor.name] &&
!stack.includes(obj[key])
) {
const nestedDiffs = diff(obj[key], newObj[key]);
const nestedDiffs = diff(obj[key], newObj[key], stack.concat(obj[key]));
diffs.push(
...nestedDiffs.map((difference) => {
difference.path.unshift(key);
Expand Down
17 changes: 17 additions & 0 deletions tests/cycles.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { test } from "uvu";
import * as assert from "uvu/assert";
import diff from "../dist/index.js";

test("Handles recursive references", () => {
const obj1 = {};
obj1.a = obj1;
assert.equal(diff(obj1, obj1), []);
});

test("Handles recursive references more than 1 level up", () => {
const obj1 = { a: {} };
obj1.a.b = obj1;
assert.equal(diff(obj1, obj1), []);
});

test.run();

0 comments on commit 3b6ab8f

Please sign in to comment.