12. Implement deepEqual(a, b) — Structural Equality

medium

The natural sequel to deep clone: instead of copying a structure, compare two. It probes the same edge-case awareness.

The idea

  1. Object.is catches the easy wins — primitives, and the tricky NaN/signed-zero cases === gets wrong.
  2. If either side is a non-object (or null), they can only match by strict equality.
  3. For two objects, equal key counts plus a recursive check on every key.

Follow-ups

  • "Arrays vs objects?" → Object.keys covers array indices, but compare Array.isArray if you want strict type matching.
  • "Dates, Maps, Sets?" → branch like deep clone does, comparing getTime() / entries.
  • "Cycles?" → carry a WeakMap/Set of visited pairs to avoid infinite recursion.

What to practice

Write the base version, then extend it to handle Date and arrays-vs-objects type mismatches.

More questions

index.js
function deepEqual(a, b) {
  // your code here
}

console.log(deepEqual({ x: 1, y: [2, 3] }, { x: 1, y: [2, 3] })); // true
console.log(deepEqual({ x: 1 }, { x: 1, y: 2 }));                  // false

Tests

Test Code

Enter JavaScript that runs after your solution. It should return a value or a Promise.