Skip to content

Commit ce20559

Browse files
committed
Fix object-array diffs
1 parent 1189922 commit ce20559

File tree

2 files changed

+18
-10
lines changed

2 files changed

+18
-10
lines changed

index.ts

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ export default function diff(
2929
obj: Record<string, any> | any[],
3030
newObj: Record<string, any> | any[],
3131
options: Partial<Options> = { cyclesFix: true },
32-
_stack: Record<string, any>[] = []
32+
_stack: Record<string, any>[] = [],
3333
): Difference[] {
3434
let diffs: Difference[] = [];
3535
const isObjArray = Array.isArray(obj);
@@ -46,32 +46,34 @@ export default function diff(
4646
continue;
4747
}
4848
const newObjKey = newObj[key];
49-
const areObjects =
50-
typeof objKey === "object" && typeof newObjKey === "object";
49+
const areCompatibleObjects =
50+
typeof objKey === "object" &&
51+
typeof newObjKey === "object" &&
52+
Array.isArray(objKey) === Array.isArray(newObjKey);
5153
if (
5254
objKey &&
5355
newObjKey &&
54-
areObjects &&
56+
areCompatibleObjects &&
5557
!richTypes[Object.getPrototypeOf(objKey)?.constructor?.name] &&
5658
(!options.cyclesFix || !_stack.includes(objKey))
5759
) {
5860
const nestedDiffs = diff(
5961
objKey,
6062
newObjKey,
6163
options,
62-
options.cyclesFix ? _stack.concat([objKey]) : []
64+
options.cyclesFix ? _stack.concat([objKey]) : [],
6365
);
6466
diffs.push.apply(
6567
diffs,
6668
nestedDiffs.map((difference) => {
6769
difference.path.unshift(path);
6870
return difference;
69-
})
71+
}),
7072
);
7173
} else if (
7274
objKey !== newObjKey &&
7375
!(
74-
areObjects &&
76+
areCompatibleObjects &&
7577
(isNaN(objKey)
7678
? objKey + "" === newObjKey + ""
7779
: +objKey === +newObjKey)

tests/arrays.js

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,15 +21,15 @@ test("nested array", () => {
2121
path: [1, 1],
2222
value: "test2",
2323
},
24-
]
24+
],
2525
);
2626
});
2727

2828
test("object in array in object", () => {
2929
assert.deepStrictEqual(
3030
diff(
3131
{ test: ["test", { test: true }] },
32-
{ test: ["test", { test: false }] }
32+
{ test: ["test", { test: false }] },
3333
),
3434
[
3535
{
@@ -38,6 +38,12 @@ test("object in array in object", () => {
3838
value: false,
3939
oldValue: true,
4040
},
41-
]
41+
],
4242
);
4343
});
44+
45+
test("array to object", () => {
46+
assert.deepStrictEqual(diff({ data: [] }, { data: { val: "test" } }), [
47+
{ type: "CHANGE", path: ["data"], value: { val: "test" }, oldValue: [] },
48+
]);
49+
});

0 commit comments

Comments
 (0)