Skip to content

Commit feb02a1

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

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
@@ -215,33 +215,24 @@ 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 */
221-
222218
// check that all of y's direct keys are in x
223-
let p;
224-
for (p in y) {
219+
for (const p in y) {
225220
if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {
226221
return false;
227222
}
228223
}
229224

230225
// 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])) {
226+
for (const p in x) {
227+
if (y.hasOwnProperty(p) !== x.hasOwnProperty(p) || !deepCompare(x[p], y[p])) {
236228
return false;
237229
}
238230
}
239231
}
240-
/* jshint +W089 */
241232
return true;
242233
}
243234

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

0 commit comments

Comments
 (0)