Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Js

Idiom #114 Test deep equality

Set boolean b to true if objects x and y contain the same values, recursively comparing all referenced elements in x and y.
Tell if the code correctly handles recursive types.

import _ from 'underscore';
const b = _.isEqual(x, y);
const b = JSON.stringify(x) === JSON.stringify(y);

Won't work for things which aren't serializable (such as functions) or recursive.
import {isDeepStrictEqual} from 'util'
const b = isDeepStrictEqual(x, y)

Only works in Node.js. This correctly handles recursive types.

Only enumerable own properties are considered, object wrappers are compared both as objects and unwrapped values, and WeakMap and WeakSet comparisons do not rely on their values.
const arrayDeepEqual = (a, b) => a.length === b.length && a.every((x, i) => deepEqual(x, b[i]))

const deepEqual = (a, b) =>
  Array.isArray(a) && Array.isArray(b)
    ? arrayDeepEqual(a, b)
    : typeof a == 'object' && a && typeof b == 'object' && b
    ? arrayDeepEqual(Object.entries(a), Object.entries(b))
    : Number.isNaN(a) && Number.isNaN(b) || a === b

const b = deepEqual(x, y)

This does not handle recursive types, Maps/Sets/Dates, the prototype/class of objects, or non-enumerable properties such as symbols.
(def b (identical? x y))

for external entities, identical will check if references point to the same object

New implementation...
< >
programming-idioms.org