Skip to content

Commit 48cce65

Browse files
author
3nprob
committed
utils: Fix bug in deepCompare which would incorrectly return objects with disjoint keys as equal
1 parent 1fbd898 commit 48cce65

File tree

2 files changed

+7
-13
lines changed

2 files changed

+7
-13
lines changed

spec/unit/utils.spec.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,9 @@ describe("utils", function() {
152152
assert.isTrue(utils.deepCompare({ a: 1, b: 2 }, { a: 1, b: 2 }));
153153
assert.isTrue(utils.deepCompare({ a: 1, b: 2 }, { b: 2, a: 1 }));
154154
assert.isFalse(utils.deepCompare({ a: 1, b: 2 }, { a: 1, b: 3 }));
155+
assert.isFalse(utils.deepCompare({ a: 1, b: 2 }, { a: 1 }));
156+
assert.isFalse(utils.deepCompare({ a: 1 }, { a: 1, b: 2 }));
157+
assert.isFalse(utils.deepCompare({ a: 1 }, { b: 1 }));
155158

156159
assert.isTrue(utils.deepCompare({
157160
1: { name: "mhc", age: 28 },

src/utils.ts

Lines changed: 4 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -214,33 +214,24 @@ export function deepCompare(x: any, y: any): boolean {
214214
}
215215
}
216216
} else {
217-
// disable jshint "The body of a for in should be wrapped in an if
218-
// statement"
219-
/* jshint -W089 */
220-
221217
// check that all of y's direct keys are in x
222-
let p;
223-
for (p in y) {
218+
for (const p in y) {
224219
if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {
225220
return false;
226221
}
227222
}
228223

229224
// finally, compare each of x's keys with y
230-
for (p in y) { // eslint-disable-line guard-for-in
231-
if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {
232-
return false;
233-
}
234-
if (!deepCompare(x[p], y[p])) {
225+
for (const p in x) {
226+
if (y.hasOwnProperty(p) !== x.hasOwnProperty(p) || !deepCompare(x[p], y[p])) {
235227
return false;
236228
}
237229
}
238230
}
239-
/* jshint +W089 */
240231
return true;
241232
}
242233

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

0 commit comments

Comments
 (0)