Skip to content

Commit

Permalink
Use fast-deep-equal
Browse files Browse the repository at this point in the history
  • Loading branch information
jennydaman committed Feb 23, 2024
1 parent adab44b commit ad26c81
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 18 deletions.
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,5 +31,8 @@
"@niivue/niivue": "^0.39.0",
"react": "^17 || ^18",
"typescript": "^5.0.0"
},
"dependencies": {
"fast-deep-equal": "^3.1.3"
}
}
7 changes: 7 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 3 additions & 18 deletions src/diff.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { HasUrlObject } from "./model.ts";
import { HasUrlObject } from "./model";
import equal from "fast-deep-equal/es6";

/**
* A special value which indicates that the difference between two objects is Irreconcilable.
Expand Down Expand Up @@ -186,30 +187,14 @@ function diffPrimitive<T extends { [key: string]: any }>(
const yKeys = Object.keys(y);
const deletedKeys = setDifference(xKeys, yKeys);
const addedKeys = setDifference(yKeys, xKeys);
const changedKeys = xKeys.filter((key) => !deepishEqual(x[key], y[key]));
const changedKeys = xKeys.filter((key) => !equal(x[key], y[key]));
const diffKeys = addedKeys.concat(changedKeys);
return {
...Object.fromEntries(deletedKeys.map((key) => [key, undefined])),
...Object.fromEntries(diffKeys.map((key) => [key, y[key]])),
};
}

/**
* Equality for arrays and primitives.
*/
function deepishEqual<T>(x: T, y: T): boolean {
if (Array.isArray(x)) {
if (!Array.isArray(y)) {
return false;
}
return zipArrays(x, y).reduce(
(same, [a, b]) => same && deepishEqual(a, b),
true,
);
}
return x === y;
}

function zipArrays<X, Y>(x: X[], y: Y[]): [X, Y][] {
return x.map((v, i) => [v, y[i]]);
}
Expand Down

0 comments on commit ad26c81

Please sign in to comment.