Skip to content

Commit c53a7f0

Browse files
committed
Performance improvments
1 parent a8c5679 commit c53a7f0

File tree

2 files changed

+31
-18
lines changed

2 files changed

+31
-18
lines changed

bench.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ async function benchmark(name, obj, newObj, exclude = []) {
1919
continue;
2020
}
2121
times[benchmark] = [];
22-
for (let i = 1; i < 100; i++) {
22+
for (let i = 1; i < 10000; i++) {
2323
let time = hrtime();
2424
benchmarks[benchmark]();
2525
times[benchmark].push(hrtime(time)[1]);

index.ts

Lines changed: 30 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,15 @@ interface Difference {
33
path: string[];
44
value?: any;
55
}
6+
interface Options {
7+
cyclesFix: boolean;
8+
}
69
const t = true;
710
const richTypes = { Date: t, RegExp: t, String: t, Number: t };
811
export default function diff(
912
obj: Record<string, any> | any[],
1013
newObj: Record<string, any> | any[],
14+
options: Partial<Options> = { cyclesFix: true },
1115
stack: Record<string, any>[] = []
1216
): Difference[] {
1317
let diffs: Difference[] = [];
@@ -17,35 +21,44 @@ export default function diff(
1721
type: "REMOVE",
1822
path: [key],
1923
});
20-
} else if (
21-
obj[key] &&
22-
newObj[key] &&
23-
typeof obj[key] === "object" &&
24-
typeof newObj[key] === "object" &&
25-
!richTypes[Object.getPrototypeOf(obj[key]).constructor.name] &&
26-
!stack.includes(obj[key])
24+
continue;
25+
}
26+
const objKey = obj[key];
27+
const newObjKey = newObj[key];
28+
const areObjects =
29+
typeof objKey === "object" && typeof newObjKey === "object";
30+
if (
31+
objKey &&
32+
newObjKey &&
33+
areObjects &&
34+
!richTypes[Object.getPrototypeOf(objKey).constructor.name] &&
35+
(options.cyclesFix ? !stack.includes(obj[key]) : true)
2736
) {
28-
const nestedDiffs = diff(obj[key], newObj[key], stack.concat([obj[key]]));
29-
diffs.push(
30-
...nestedDiffs.map((difference) => {
37+
const nestedDiffs = diff(
38+
objKey,
39+
newObjKey,
40+
options,
41+
options.cyclesFix ? stack.concat([objKey]) : []
42+
);
43+
diffs.push.apply(
44+
nestedDiffs.map((difference) => {
3145
difference.path.unshift(key);
3246
return difference;
3347
})
3448
);
3549
} else if (
36-
obj[key] !== newObj[key] &&
50+
objKey !== newObjKey &&
3751
!(
38-
typeof obj[key] === "object" &&
39-
typeof newObj[key] === "object" &&
40-
(isNaN(obj[key])
41-
? obj[key] + "" === newObj[key] + ""
42-
: +obj[key] === +newObj[key])
52+
areObjects &&
53+
(isNaN(objKey)
54+
? objKey + "" === newObjKey + ""
55+
: +objKey === +newObjKey)
4356
)
4457
) {
4558
diffs.push({
4659
path: [key],
4760
type: "CHANGE",
48-
value: newObj[key],
61+
value: newObjKey,
4962
});
5063
}
5164
}

0 commit comments

Comments
 (0)