Skip to content

Commit 7589dd4

Browse files
committed
improve deepEqual to handle Set & Map
1 parent 6c0aabd commit 7589dd4

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

src/lib/deepEqual.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,16 @@ export function deepEqual(a: any, b: any): boolean {
3030
return a.source === b.source && a.flags === b.flags;
3131
}
3232

33+
// Handle special case for Set
34+
if (a instanceof Set && b instanceof Set) {
35+
return deepEqual([...a], [...b]);
36+
}
37+
38+
// Handle special case for Map
39+
if (a instanceof Map && b instanceof Map) {
40+
return deepEqual(Object.fromEntries(a), Object.fromEntries(b));
41+
}
42+
3343
// If a or b are not objects or null, they can't be deeply equal
3444
if (
3545
typeof a !== 'object' ||

test/lib/deepEqual.test.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,29 @@ describe('deepEqual', () => {
118118
});
119119
});
120120

121+
describe('Map', () => {
122+
it.each`
123+
a | b | expected
124+
${new Set()} | ${new Set()} | ${true}
125+
${new Set(['a'])} | ${new Set(['b'])} | ${false}
126+
${new Set(['a'])} | ${new Set(['a', 'b'])} | ${false}
127+
${new Set(['a'])} | ${['a']} | ${false}
128+
`('returns $expected for a: $a and b: $b', ({ a, b, expected }) => {
129+
expect(deepEqual(a, b)).toBe(expected);
130+
});
131+
});
132+
133+
describe('Map', () => {
134+
it.each`
135+
a | b | expected
136+
${new Map()} | ${new Map()} | ${true}
137+
${new Map([['a', 1]])} | ${new Map([['b', 1]])} | ${false}
138+
${new Map([['a', 1]])} | ${new Map([['a', 1], ['b', 1]])} | ${false}
139+
`('returns $expected for a: $a and b: $b', ({ a, b, expected }) => {
140+
expect(deepEqual(a, b)).toBe(expected);
141+
});
142+
});
143+
121144
describe('Functions', () => {
122145
const funcA = () => 'test';
123146
const funcB = () => 'test';

0 commit comments

Comments
 (0)