Skip to content
Onsite

Deep Diff of Two Objects

MediumP3Coding

Implement deepDiff(a, b), which compares two values and returns an array of change records describing how to get from a to b.

Each record is one of:

  • { path, type: 'added', newValue }: the key or index exists only in b,
  • { path, type: 'removed', oldValue }: it exists only in a,
  • { path, type: 'changed', oldValue, newValue }: it exists in both with different values.

Rules:

  • path is a string of keys joined by dots, with array indexes as numbers: "user.tags.1". A difference at the root has path "".
  • Two plain objects are compared key by key, and two arrays index by index, recursively. Only the innermost differing values are reported.
  • Everything else (primitives, dates, functions, an object compared with an array...) is compared with Object.is; if different, report one changed record for that path with the whole values.
  • Order of records: first, for each key of a in order, its removed or changed records; then, for each key only in b, its added record.
  • Equal values return []. A key whose value is undefined exists, so {a: undefined} versus {} is a removal.

Example 1

Input
deepDiff({ a: 1, b: { c: 2 } }, { a: 1, b: { c: 3 }, d: 4 })
Output
[{ path: 'b.c', type: 'changed', oldValue: 2, newValue: 3 }, { path: 'd', type: 'added', newValue: 4 }]

Constraints

  • Total number of keys <= 10^4
  • No circular references.
  • Object keys do not contain dots.

Hints

Run checks the 3 visible tests, Submit all 10.