1 min readDec 21, 2023
The introduced implementation e.g. fails for 0 vs -0 which should not be equal (it is not the same), but says it is, and for Number.NaN which can not be compared to itself, but actually is the same. For the latter case the function returns false but should return true.
There is more to optimize. An already more reliable implementation which exclusively targets non-cyclic data-structures (and nothing else) could look like follows ...
function isDeepDataStructureEquality(a, b) {
let isEqual = Object.is(a, b);
if (!isEqual) {
if (Array.isArray(a) && Array.isArray(b)) {
isEqual = (a.length === b.length) && a.every(
(item, idx) => isDeepDataStructureEquality(item, b[idx])
);
} else if (
a && b
&& (typeof a === 'object')
&& (typeof b === 'object')
) {
const aKeys = Object.keys(a);
const bKeys = Object.keys(b);
isEqual = (aKeys.length === bKeys.length) && aKeys.every(
(key, idx) => isDeepDataStructureEquality(a[key], b[key])
);
}
}
return isEqual;
}