Skip to content

Commit 32f0f96

Browse files
author
3nprob
committed
utils: Fix bug in deepCompare which would incorrectly return objects with disjoint keys as equal
1 parent 9eb7290 commit 32f0f96

File tree

2 files changed

+7
-12
lines changed

2 files changed

+7
-12
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 & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -215,33 +215,25 @@ export function deepCompare(x: any, y: any): boolean {
215215
}
216216
}
217217
} else {
218-
// disable jshint "The body of a for in should be wrapped in an if
219-
// statement"
220-
/* jshint -W089 */
221218

222219
// check that all of y's direct keys are in x
223-
let p;
224-
for (p in y) {
220+
for (const p in y) {
225221
if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {
226222
return false;
227223
}
228224
}
229225

230226
// finally, compare each of x's keys with y
231-
for (p in y) { // eslint-disable-line guard-for-in
232-
if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {
233-
return false;
234-
}
235-
if (!deepCompare(x[p], y[p])) {
227+
for (const p in x) {
228+
if (y.hasOwnProperty(p) !== x.hasOwnProperty(p) || !deepCompare(x[p], y[p])) {
236229
return false;
237230
}
238231
}
239232
}
240-
/* jshint +W089 */
241233
return true;
242234
}
243235

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

0 commit comments

Comments
 (0)