Class: Hokusai::Diff
- Inherits:
-
Object
- Object
- Hokusai::Diff
- Defined in:
- ui/src/hokusai/diff.rb
Instance Attribute Summary collapse
-
#after ⇒ Object
readonly
Returns the value of attribute after.
-
#before ⇒ Object
readonly
Returns the value of attribute before.
-
#insertions ⇒ Object
readonly
Returns the value of attribute insertions.
Instance Method Summary collapse
-
#initialize(before, after) ⇒ Diff
constructor
A new instance of Diff.
- #map(list) ⇒ Object
- #patch ⇒ Object
Constructor Details
#initialize(before, after) ⇒ Diff
Returns a new instance of Diff.
42 43 44 45 46 |
# File 'ui/src/hokusai/diff.rb', line 42 def initialize(before, after) @before = before @after = after @insertions = {} end |
Instance Attribute Details
#after ⇒ Object (readonly)
Returns the value of attribute after.
40 41 42 |
# File 'ui/src/hokusai/diff.rb', line 40 def after @after end |
#before ⇒ Object (readonly)
Returns the value of attribute before.
40 41 42 |
# File 'ui/src/hokusai/diff.rb', line 40 def before @before end |
#insertions ⇒ Object (readonly)
Returns the value of attribute insertions.
40 41 42 |
# File 'ui/src/hokusai/diff.rb', line 40 def insertions @insertions end |
Instance Method Details
#map(list) ⇒ Object
48 49 50 51 52 53 54 55 |
# File 'ui/src/hokusai/diff.rb', line 48 def map(list) memo = {} list.each_with_index do |(key, value), index| memo[key] = { value: value, index: index } end memo end |
#patch ⇒ Object
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 |
# File 'ui/src/hokusai/diff.rb', line 57 def patch i = 0 deletions = 0 mapbefore = map(before) mapafter = map(after) while i < after.size # left right # [d, a, c] [(c), e, a, b] # # 1. [c, a] [c, (e), a] # # 2. [c, e, a] [c, e, b, (a),] # # 3. [c, e, b, a] # # is value (c) in left? # yes -> # is left[0] (a) in right? # yes -> move c to 0, move a to 2 # no -> delete a, move c to 0 # akey, value = after[i] # b ckey, current = before[i] || nil # a if bi = mapbefore.delete(akey) # 2 if bi[:index] != i # true (2 != 0) if mapafter[ckey] # true # move a to 2 before[bi[:index]] = [ckey, current] # before[2] = a # update index mapbefore[ckey] = { index: bi, value: current } # move c to 0 yield MovePatch.new(from: bi, to: i) else yield MovePatch.new(from: bi, to: i, delete: true) mapbefore[ckey] = nil deletions += 1 # next end elsif value != current yield UpdatePatch.new(target: i, value: value) end else # insert logic if mapafter[ckey] before[i + 1] = [ckey, current] mapbefore[ckey] = { index: i + 1, value: current } yield InsertPatch.new(target: i, value: value) else yield InsertPatch.new(target: i, value: value, delete: true) mapbefore[ckey] = nil end end i += 1 end mapbefore.values.each do |value| next if value.nil? yield DeletePatch.new(value[:index]) unless value[:index].nil? end end |