MediumPro challengeJavaScriptTypeScript

Diff Component Trees

ReactDiffAlgorithms

Compare two virtual node trees. Each node: { type, props, children }.

Return list of operations needed to update prev → next:

  • { op: 'replace', path } — type changed.
  • { op: 'props', path } — props changed (any key differs).
  • No op if identical.

Path is a dot-joined string of indices, e.g. '0.1' for second child of first.

Sample tests

Test #1Identical trees
Input: [{"type":"div","props":{},"children":[]},{"type":"div","props":{},"children":[]}]
Output: []
Test #2Type changed
Input: [{"type":"div","props":{},"children":[]},{"type":"span","props":{},"children":[]}]
Output: [{"op":"replace","path":"0"}]
Test #3Props changed
Input: [{"type":"div","props":{"id":"a"},"children":[]},{"type":"div","props":{"id":"b"},"children":[]}]
Output: [{"op":"props","path":"0"}]
Test #4Child props changed
Input: [{"type":"ul","props":{},"children":[{"type":"li","props":{},"children":[]}]},{"type":"ul","props":{},"children":[{"type":"li","props":{"id":"x"},"children":[]}]}]
Output: [{"op":"props","path":"0.0"}]
Test #5Child type changed
Input: [{"type":"div","props":{},"children":[{"type":"a","props":{},"children":[]}]},{"type":"div","props":{},"children":[{"type":"b","props":{},"children":[]}]}]
Output: [{"op":"replace","path":"0.0"}]