Skip to the solution
HardDSA13 min read

Implement deepEqual(a, b) handling NaN, -0, Dates, RegExp & circular refs

586 views

The problem

Problem, as an interviewer would state it: "Create isEqual (deep equality) that correctly handles NaN === NaN, -0 versus +0, Dates, RegExps, arrays, plain objects, and circular references. Discuss edge cases, runtime, and alternatives."

Examples:

Code
deepEqual(NaN, NaN);                        // true   (=== says false)
deepEqual(0, -0);                           // false  (=== says true)
deepEqual({ a: [1, new Date(0)] }, { a: [1, new Date(0)] });   // true
const x = { v: 1 }; x.self = x;  const y = { v: 1 }; y.self = y;
deepEqual(x, y);                            // true, and it terminates

Clarifying questions expected:

  • Which equality for primitives (Object.is), and do prototypes and key order matter?
  • Should Map and Set ignore order, and how are object members matched?
  • What should two circular structures do, and how much data will it see?

Code / implementation expected: Yes — real code, checked against a trusted implementation and on cycles and shared structure.

  • deep-equal
  • NaN
  • -0
  • edge-cases

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

13 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: deepEqual settles every semantic question, survives cycles, passes property tests, and the memoised version removes the exponential blow-up

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 150 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextHard

Graph dfs traversal

Continue