Problem
Comparing state snapshots, memoizing selectors and writing test assertions all need a deep equality check in JavaScript, because === only tells you whether two objects are the same reference.
Write a function deepEqual(a, b) that returns true when a and b are structurally equal by value, and false otherwise.
Requirements
- Primitives are equal when they are strictly equal (
1vs"1"isfalse). NaNis considered equal toNaN.nullandundefinedare only equal to themselves; comparingnullwith an object returnsfalse.- Two plain objects are equal when they have the same set of own enumerable keys and every corresponding value is deeply equal. Key order does not matter.
- Two arrays are equal when they have the same length and equal elements at every index.
- Nesting can be arbitrarily deep and can mix objects and arrays.
Example
deepEqual(3, 3); // true
deepEqual(NaN, NaN); // true
deepEqual({ x: 1, y: 2 }, { y: 2, x: 1 }); // true
deepEqual({ user: { tags: ["a", "b"] } },
{ user: { tags: ["a", "b"] } }); // true
deepEqual({ x: 1 }, { x: 1, y: undefined }); // false
deepEqual(["a", "b"], ["b", "a"]); // false
deepEqual({ x: null }, { x: {} }); // false
Follow-ups
- How would you compare
Date,RegExp,MapandSetvalues correctly? - What happens with circular references, and how would you support them?