Module: Plushie::Tree::Diff

Defined in:
lib/plushie/tree/diff.rb

Overview

Tree diffing algorithm.

Produces patch operations (replace_node, update_props, insert_child, remove_child) per the wire protocol spec. Uses LIS-based (Longest Increasing Subsequence) algorithm for minimal patches on reordered children.

Class Method Summary collapse

Class Method Details

.diff(old_tree, new_tree) ⇒ Array<Hash>

Diff two normalized trees.

Parameters:

  • old_tree (Node, nil)
  • new_tree (Node, nil)

Returns:

  • (Array<Hash>)

    patch operations



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/plushie/tree/diff.rb', line 16

def self.diff(old_tree, new_tree)
  return [] if old_tree.nil? && new_tree.nil?

  if old_tree.nil?
    return [{"op" => "replace_node", "path" => [], "node" => Tree.node_to_wire(new_tree)}] if new_tree # : Node

    return []
  end

  if new_tree.nil?
    return [{"op" => "replace_node", "path" => [],
             "node" => Tree.node_to_wire(Node.new(id: "root", type: "container"))}]
  end
  if old_tree.id != new_tree.id
    return [{"op" => "replace_node", "path" => [],
             "node" => Tree.node_to_wire(new_tree)}]
  end

  diff_node(old_tree, new_tree, [])
end