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 inb,{ path, type: 'removed', oldValue }: it exists only ina,{ path, type: 'changed', oldValue, newValue }: it exists in both with different values.
Rules:
pathis 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 onechangedrecord for that path with the whole values. - Order of records: first, for each key of
ain order, its removed or changed records; then, for each key only inb, its added record. - Equal values return
[]. A key whose value isundefinedexists, 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
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 10. ⌘Enter runs, ⌘⇧Enter submits.