Skip to content

Commit 1409d2d

Browse files
committed
Array number key INDEV
1 parent 6c551e6 commit 1409d2d

File tree

2 files changed

+11
-10
lines changed

2 files changed

+11
-10
lines changed

index.ts

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
interface Difference {
22
type: "CREATE" | "REMOVE" | "CHANGE";
3-
path: string[];
3+
path: (string | number)[];
44
value?: any;
55
}
66
interface Options {
@@ -16,14 +16,15 @@ export default function diff(
1616
): Difference[] {
1717
let diffs: Difference[] = [];
1818
for (const key in obj) {
19+
const objKey = obj[key];
20+
const path = Array.isArray(obj) ? +key : key;
1921
if (!(key in newObj)) {
2022
diffs.push({
2123
type: "REMOVE",
22-
path: [key],
24+
path: [path],
2325
});
2426
continue;
2527
}
26-
const objKey = obj[key];
2728
const newObjKey = newObj[key];
2829
const areObjects =
2930
typeof objKey === "object" && typeof newObjKey === "object";
@@ -32,7 +33,7 @@ export default function diff(
3233
newObjKey &&
3334
areObjects &&
3435
!richTypes[Object.getPrototypeOf(objKey).constructor.name] &&
35-
(options.cyclesFix ? !_stack.includes(obj[key]) : true)
36+
(options.cyclesFix ? !_stack.includes(objKey) : true)
3637
) {
3738
const nestedDiffs = diff(
3839
objKey,
@@ -43,7 +44,7 @@ export default function diff(
4344
diffs.push.apply(
4445
diffs,
4546
nestedDiffs.map((difference) => {
46-
difference.path.unshift(key);
47+
difference.path.unshift(path);
4748
return difference;
4849
})
4950
);
@@ -57,7 +58,7 @@ export default function diff(
5758
)
5859
) {
5960
diffs.push({
60-
path: [key],
61+
path: [path],
6162
type: "CHANGE",
6263
value: newObjKey,
6364
});
@@ -67,7 +68,7 @@ export default function diff(
6768
if (!(key in obj)) {
6869
diffs.push({
6970
type: "CREATE",
70-
path: [key],
71+
path: [Array.isArray(newObj) ? +key : key],
7172
value: newObj[key],
7273
});
7374
}

tests/arrays.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ test("top level array & array diff", () => {
66
assert.equal(diff(["test", "testing"], ["test"]), [
77
{
88
type: "REMOVE",
9-
path: ["1"],
9+
path: [1],
1010
},
1111
]);
1212
});
@@ -15,7 +15,7 @@ test("nested array", () => {
1515
assert.equal(diff(["test", ["test"]], ["test", ["test", "test2"]]), [
1616
{
1717
type: "CREATE",
18-
path: ["1", "1"],
18+
path: [1, 1],
1919
value: "test2",
2020
},
2121
]);
@@ -30,7 +30,7 @@ test("object in array in object", () => {
3030
[
3131
{
3232
type: "CHANGE",
33-
path: ["test", "1", "test"],
33+
path: ["test", 1, "test"],
3434
value: false,
3535
},
3636
]

0 commit comments

Comments
 (0)