JavaScriptFundamental (ES6), part 2
Deep equal with NaN, -0 and cycles in JavaScript
112 Deep equality that survives a cycle
hardWrite deepEqual(a, b) properly. Handle primitives with NaN and negative zero, arrays, plain objects with keys in a different order, Date, RegExp, Map and Set, and objects that reference themselves. Show why comparing JSON.stringify output is not a substitute. Keep a record of the pairs you are already in the middle of comparing so a cycle terminates instead of overflowing the stack, and be honest in the note about the one case a straightforward implementation still gets wrong.
Stuck? Three hints, smallest first
- 1.
Object.ishandles the primitive cases you would otherwise special-case, includingNaNand-0. - 2. Compare the key sets, not the key lists, and check that
bactually owns each key rather than inheriting it —undefinedand missing are not the same. - 3. For cycles, keep a
Mapfrom each visitedato thebit was paired with. Meeting the same pair again means assume equal: anything else and you never return.
function deepEqual(a, b, seen = new Map()) {
if (Object.is(a, b)) return true; // covers NaN, and -0 vs 0
if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false;
if (Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) return false;
if (seen.get(a) === b) return true; // this pair is already in flight
seen.set(a, b);
if (a instanceof Date) return a.getTime() === b.getTime();
if (a instanceof RegExp) return a.source === b.source && a.flags === b.flags;
if (a instanceof Map) {
if (a.size !== b.size) return false;
for (const [key, value] of a) {
if (!b.has(key)) return false; // keys matched by identity
if (!deepEqual(value, b.get(key), seen)) return false;
}
return true;
}
if (a instanceof Set) {
if (a.size !== b.size) return false;
for (const value of a) if (!b.has(value)) return false;
return true;
}
if (Array.isArray(a)) {
if (a.length !== b.length) return false;
for (let i = 0; i < a.length; i++) if (!deepEqual(a[i], b[i], seen)) return false;
return true;
}
const keysA = Object.keys(a);
const keysB = Object.keys(b);
if (keysA.length !== keysB.length) return false;
for (const key of keysA) {
if (!Object.prototype.hasOwnProperty.call(b, key)) return false;
if (!deepEqual(a[key], b[key], seen)) return false;
}
return true;
}
const attempt = (fn) => { try { return fn(); } catch (err) { return err.name; } };
const order1 = { till: 'Balogun 1', items: [{ sku: 'ADR-1', kobo: 450000 }], staff: { name: 'Adaeze' } };
const order2 = { staff: { name: 'Adaeze' }, items: [{ kobo: 450000, sku: 'ADR-1' }], till: 'Balogun 1' };
const reordered = [deepEqual(order1, order2), JSON.stringify(order1) === JSON.stringify(order2)];
const nudged = { ...order2, items: [{ sku: 'ADR-1', kobo: 450001 }] };
const oneKoboOut = deepEqual(order1, nudged);
const nanCase = [deepEqual({ reading: NaN }, { reading: NaN }), JSON.stringify({ reading: NaN })];
const zeroCase = [deepEqual({ drift: 0 }, { drift: -0 }), Object.is(0, -0)];
const missingKey = [deepEqual({ a: 1, b: undefined }, { a: 1 }), JSON.stringify({ a: 1, b: undefined }) === JSON.stringify({ a: 1 })];
const dates = [deepEqual(new Date('2024-03-01T00:00:00Z'), new Date('2024-03-01T00:00:00Z')), deepEqual(new Date('2024-03-01T00:00:00Z'), new Date('2024-03-02T00:00:00Z'))];
const patterns = [deepEqual(/ade/gi, /ade/gi), deepEqual(/ade/g, /ade/gi)];
const arrayVsObject = deepEqual([1, 2], { 0: 1, 1: 2, length: 2 });
const maps = [
deepEqual(new Map([['a', 1], ['b', { n: 2 }]]), new Map([['b', { n: 2 }], ['a', 1]])),
deepEqual(new Map([['a', 1]]), new Map([['a', 2]])),
];
const sets = [deepEqual(new Set([1, 2, 3]), new Set([3, 2, 1])), deepEqual(new Set([1, 2]), new Set([1, 2, 3]))];
// Two cycles built independently, and one built differently.
const left = { name: 'Lagos' };
left.self = left;
left.pair = { name: 'Abuja', back: left };
const right = { name: 'Lagos' };
right.self = right;
right.pair = { name: 'Abuja', back: right };
const cyclesMatch = deepEqual(left, right);
const wrong = { name: 'Lagos' };
wrong.self = wrong;
wrong.pair = { name: 'Kano', back: wrong };
const cyclesDiffer = deepEqual(left, wrong);
const stringifyGivesUp = attempt(() => JSON.stringify(left));
// The limitation: Map keys are matched by identity, not by value.
const keyedByObject = deepEqual(
new Map([[{ sku: 'ADR-1' }, 3]]),
new Map([[{ sku: 'ADR-1' }, 3]])
);
const sameKeyObject = (() => {
const key = { sku: 'ADR-1' };
return deepEqual(new Map([[key, 3]]), new Map([[key, 3]]));
})();
console.log('reordered keys :', reordered);
console.log('cycles :', cyclesMatch, cyclesDiffer, '| stringify:', stringifyGivesUp);
console.log('object map key :', keyedByObject, 'vs the same key object:', sameKeyObject);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('key order is irrelevant to deepEqual, and decisive for JSON.stringify', reordered, [true, false]);
test('one kobo of difference three levels down is still a difference', oneKoboOut, false);
test('NaN equals NaN here though JSON turns it into null, and 0 is not -0', [nanCase, zeroCase], [[true, '{"reading":null}'], [false, false]]);
test('a key present but undefined is not the same as a key absent, which JSON cannot see', missingKey, [false, true]);
test('Date and RegExp are compared by value, not by reference', [dates, patterns], [[true, false], [true, false]]);
test('an array is never equal to an array-like object: the prototypes differ', arrayVsObject, false);
test('Map and Set are compared by content, in any order, and by size', [maps, sets], [[true, false], [true, false]]);
test('two independently built cyclic objects compare equal, where stringify throws', [cyclesMatch, cyclesDiffer, stringifyGivesUp], [true, false, 'TypeError']);
test('but a Map keyed by an equivalent object is reported unequal, unless the key is the same object', [keyedByObject, sameKeyObject], [false, true]);
JSON.stringify(a) === JSON.stringify(b) is the comparison everybody reaches for and it is wrong in five different ways, four of them asserted here: it depends on key insertion order, it turns NaN into null, it drops keys whose value is undefined so {a:1,b:undefined} and {a:1} serialise identically, and it throws outright on a cycle. It also silently discards functions and symbol keys. It is fine for a cache key over data you control and unsafe as an equality test.
The cycle handling is three lines and worth understanding rather than memorising. seen maps each a already being compared to the b it was paired with; meeting that same pair again means you are back where you started, so you return true and let the rest of the comparison decide. That is not a guess — if some other part of the structure differs, that comparison fails and the whole thing is false, which the cyclesDiffer assertion confirms with a cycle whose partner is named Kano instead of Abuja.
The last assertion is the limitation to be honest about. Map.prototype.has and Set.prototype.has use SameValueZero, so a key or member that is an object matches only itself. Two maps with equivalent but distinct object keys are reported unequal, and fixing it properly means finding a perfect matching between the two key sets — for sets of objects that is bipartite matching, which is why most libraries either do it in O(n²) or document the same restriction. The prototype check has a similar sharp edge in its favour: it is what makes an array unequal to an array-like, and it also means an object made with Object.create(null) never equals a plain {}.