From e025da1ccbda2e7e96b1de67d5b025913e38855d Mon Sep 17 00:00:00 2001 From: Mradul Singh Date: Sat, 14 Nov 2026 19:01:36 +0530 Subject: [PATCH] fix(isEqual): compare key sets and reject object vs array The object branch only checked that both sides had the same number of keys, then compared a[key] with b[key] for the keys of a. A missing key in b reads as undefined, so { a: undefined } equalled { b: 1 }. An array also passed as an object with index keys, so {} equalled []. Fixes #829 --- src/isEqual.ts | 9 ++++++++- src/test/isEqual.test.ts | 18 ++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/src/isEqual.ts b/src/isEqual.ts index a4a29b79..262bce8b 100644 --- a/src/isEqual.ts +++ b/src/isEqual.ts @@ -36,11 +36,18 @@ function isEqual(obj1: any, obj2: any, shallow = false): boolean { return true; } if (a && b && typeof a === 'object' && typeof b === 'object') { + if (Array.isArray(b)) { + return false; + } const keys = Object.keys(a); if (keys.length !== Object.keys(b).length) { return false; } - return keys.every(key => deepEqual(a[key], b[key], newLevel)); + return keys.every( + key => + Object.prototype.hasOwnProperty.call(b, key) && + deepEqual(a[key], b[key], newLevel), + ); } // other return false; diff --git a/src/test/isEqual.test.ts b/src/test/isEqual.test.ts index 6d9c012c..41b92183 100644 --- a/src/test/isEqual.test.ts +++ b/src/test/isEqual.test.ts @@ -94,6 +94,24 @@ describe('isEqual', () => { expect(valueIsEqual).toBe(false); }); + it('should not equal when keys differ but counts match', () => { + expect(isEqual({ a: undefined }, { b: 1 })).toBe(false); + expect(isEqual({ a: 1, b: undefined }, { a: 1, c: 2 })).toBe(false); + expect(isEqual({ a: undefined }, { b: undefined })).toBe(false); + expect(isEqual({ a: { b: undefined } }, { a: { c: 1 } })).toBe(false); + }); + + it('should not equal an object and an array', () => { + expect(isEqual({}, [])).toBe(false); + expect(isEqual({ 0: 1 }, [1])).toBe(false); + expect(isEqual([1], { 0: 1 })).toBe(false); + expect(isEqual({ a: {} }, { a: [] })).toBe(false); + }); + + it('should equal objects with undefined values on the same keys', () => { + expect(isEqual({ a: undefined, b: 1 }, { b: 1, a: undefined })).toBe(true); + }); + it('should not equal 6', () => { obj.obj = obj; const obj2 = { a: 1, b: 2, c: [1, 2], obj: null };