Code Lab

Mode entretien. Minuteur de 20 min, sans indices ni autocomplétion

Deep equal

DifficileObjects20 min

Write a function deepEqual(a, b) that returns true when two values are equal all the way down, like two API responses with the same data, and false otherwise.

  • The values are what JSON.parse gives: plain objects, arrays, strings, numbers, booleans and null. No undefined, functions, dates or NaN.
  • Strings, numbers, booleans and null are equal when === says so: 1 and '1' are different, 0 and false are different.
  • Two arrays are equal when they have the same length and equal items in the same order.
  • Two objects are equal when they have the same keys and equal values for every key. The order of the keys does not matter: { a: 1, b: 2 } equals { b: 2, a: 1 }.
  • An array never equals an object, and null never equals an object: typeof null is 'object', watch out.
  • Values can be nested to any depth.

Exemples

deepEqual({ id: 7, tags: [1, 2] }, { tags: [1, 2], id: 7 })

Renvoie true

deepEqual({ a: 1 }, { a: 1, b: 2 })

Renvoie false

deepEqual([1, [2, 3]], [1, [3, 2]])

Renvoie false

Source

Chargement de l'éditeur...
  1. EntréedeepEqual({ id: 7, tags: [ 1, 2 ] }, { tags: [ 1, 2 ], id: 7 })
    Attendutrue
  2. EntréedeepEqual({ a: 1 }, { a: 1, b: 2 })
    Attendufalse
  3. EntréedeepEqual([ 1, [ 2, 3 ] ], [ 1, [ 3, 2 ] ])
    Attendufalse

Les tests cachés se lancent à la soumission