Skip to content

Commit

Permalink
utils: Fix bug in deepCompare which would incorrectly return objects …
Browse files Browse the repository at this point in the history
…with disjoint keys as equal
  • Loading branch information
3nprob committed Aug 30, 2022
1 parent 1fbd898 commit 48cce65
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 13 deletions.
3 changes: 3 additions & 0 deletions spec/unit/utils.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,9 @@ describe("utils", function() {
assert.isTrue(utils.deepCompare({ a: 1, b: 2 }, { a: 1, b: 2 }));
assert.isTrue(utils.deepCompare({ a: 1, b: 2 }, { b: 2, a: 1 }));
assert.isFalse(utils.deepCompare({ a: 1, b: 2 }, { a: 1, b: 3 }));
assert.isFalse(utils.deepCompare({ a: 1, b: 2 }, { a: 1 }));
assert.isFalse(utils.deepCompare({ a: 1 }, { a: 1, b: 2 }));
assert.isFalse(utils.deepCompare({ a: 1 }, { b: 1 }));

assert.isTrue(utils.deepCompare({
1: { name: "mhc", age: 28 },
Expand Down
17 changes: 4 additions & 13 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,33 +214,24 @@ export function deepCompare(x: any, y: any): boolean {
}
}
} else {
// disable jshint "The body of a for in should be wrapped in an if
// statement"
/* jshint -W089 */

// check that all of y's direct keys are in x
let p;
for (p in y) {
for (const p in y) {
if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {
return false;
}
}

// finally, compare each of x's keys with y
for (p in y) { // eslint-disable-line guard-for-in
if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {
return false;
}
if (!deepCompare(x[p], y[p])) {
for (const p in x) {
if (y.hasOwnProperty(p) !== x.hasOwnProperty(p) || !deepCompare(x[p], y[p])) {
return false;
}
}
}
/* jshint +W089 */
return true;
}

// Dev note: This returns a tuple, but jsdoc doesn't like that. https://github.com/jsdoc/jsdoc/issues/1703
// Dev note: This returns an array of tuples, but jsdoc doesn't like that. https://github.com/jsdoc/jsdoc/issues/1703
/**
* Creates an array of object properties/values (entries) then
* sorts the result by key, recursively. The input object must
Expand Down

0 comments on commit 48cce65

Please sign in to comment.