Modo entrevista. Cronômetro de 20 min, sem dicas e sem autocompletar
Deep equal
DifícilObjects20 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.parsegives: plain objects, arrays, strings, numbers, booleans and null. Noundefined, functions, dates orNaN. - Strings, numbers, booleans and
nullare equal when===says so:1and'1'are different,0andfalseare 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
nullnever equals an object:typeof nullis'object', watch out. - Values can be nested to any depth.
Exemplos
deepEqual({ id: 7, tags: [1, 2] }, { tags: [1, 2], id: 7 })Retorna true
deepEqual({ a: 1 }, { a: 1, b: 2 })Retorna false
deepEqual([1, [2, 3]], [1, [3, 2]])Retorna false
Carregando o editor...
- Entrada
deepEqual({ id: 7, tags: [ 1, 2 ] }, { tags: [ 1, 2 ], id: 7 })Esperadotrue - Entrada
deepEqual({ a: 1 }, { a: 1, b: 2 })Esperadofalse - Entrada
deepEqual([ 1, [ 2, 3 ] ], [ 1, [ 3, 2 ] ])Esperadofalse
Os testes ocultos rodam no envio