Skip to content

Commit

Permalink
fix deepEqual
Browse files Browse the repository at this point in the history
  • Loading branch information
afshinm committed Jan 15, 2024
1 parent ea1eedb commit 0bdf260
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 2 deletions.
42 changes: 40 additions & 2 deletions src/util/deepEqual.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,44 @@
* @param b right object
* @returns
*/
export function deepEqual<A, B>(a: A, b: B) {
return JSON.stringify(a) === JSON.stringify(b);
export function deepEqual<A, B>(obj1: A, obj2: B) {
// If objects are not the same type, return false
if (typeof obj1 !== typeof obj2) {
return false;
}
// If objects are both null or undefined, return true
if (obj1 === null && obj2 === null) {
return true;
}
// If objects are both primitive types, compare them directly
if (typeof obj1 !== 'object') {
// eslint-disable-next-line
// @ts-ignore
return obj1 === obj2;
}
// If objects are arrays, compare their elements recursively
if (Array.isArray(obj1) && Array.isArray(obj2)) {
if (obj1.length !== obj2.length) {
return false;
}
for (let i = 0; i < obj1.length; i++) {
if (!deepEqual(obj1[i], obj2[i])) {
return false;
}
}
return true;
}
// If objects are both objects, compare their properties recursively
const keys1 = Object.keys(obj1);
const keys2 = Object.keys(obj2);
if (keys1.length !== keys2.length) {
return false;
}
for (const key of keys1) {
// eslint-disable-next-line no-prototype-builtins
if (!obj2.hasOwnProperty(key) || !deepEqual(obj1[key], obj2[key])) {
return false;
}
}
return true;
}
28 changes: 28 additions & 0 deletions tests/jest/util/deepEqual.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { deepEqual } from '../../../src/util/deepEqual';

describe('deepEqual', () => {
it('should return true when objects are the same', () => {
const result = deepEqual({ a: 42 }, { a: 42 });
expect(result).toBeTrue();
});

it('should return false when objects are not the same', () => {
const result = deepEqual({ b: 42 }, { a: 42 });
expect(result).toBeFalse();
});

it('should return true when nested objects are the same', () => {
const result = deepEqual({ a: 42, c: { a: 24 } }, { a: 42, c: { a: 24 } });
expect(result).toBeTrue();
});

it('should return false when nested objects not are the same', () => {
const result = deepEqual({ a: 42, c: { x: 24 } }, { a: 42, c: { a: 24 } });
expect(result).toBeFalse();
});

it('should return true when objects have functions', () => {
const result = deepEqual({ a: 42, c: jest.fn() }, { a: 42, c: jest.fn() });
expect(result).toBeFalse();
});
});

0 comments on commit 0bdf260

Please sign in to comment.