Deeply compare values including NaN, null, arrays, and objects
Implement a deepEquals function capable of comparing two inputs, which can vary widely in type and structure, including null, undefined, objects, arrays, NaN, and primitives (such as numbers, strings, and booleans). The function should accurately determine whether the two inputs are deeply equal, meaning they are structurally identical and contain the same values at every level of nesting. Note that Object.is() handles edge cases such as NaN, which matters when you write deep equals in JavaScript.
The challenge lies in handling the nuanced differences between JavaScript data types and their comparisons. For instance:
NaN values, which by default are not equal to themselves.null and undefined.Examples of expected behavior:
deepEquals(NaN, NaN) // true
deepEquals([1, 2, [3]], [1, 2, [3]]) // true
deepEquals({ a: 1, b: { c: 2 } }, { a: 1, b: { c: 2 } }) // true
deepEquals(null, undefined) // false
deepEquals([1, 2, 3], { 0: 1, 1: 2, 2: 3 }) // false
This function is not only a powerful tool for JavaScript developers to accurately compare complex structures but also serves as an excellent exercise in understanding JavaScript’s type coercion and equality comparisons.