Class: Editeur::Differ

Inherits:
Object
  • Object
show all
Defined in:
lib/editeur/differ.rb

Instance Method Summary collapse

Constructor Details

#initialize(right_reader, left_reader) ⇒ Differ



5
6
7
8
9
10
# File 'lib/editeur/differ.rb', line 5

def initialize(right_reader, left_reader)
  @right_reader = right_reader
  @left_reader = left_reader 
  @left_lines = []
  @right_lines = []
end

Instance Method Details

#diffObject



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/editeur/differ.rb', line 34

def diff
  for r in @right_reader
    @right_lines << r
  end
  for l in @left_reader
    @left_lines << l
  end

  lcs = Diff::LCS.LCS @left_lines, @right_lines
 
  diff_left = subtract! @left_lines, lcs
  diff_right = subtract! @right_lines, lcs

  emit(diff_left, diff_right)
end

#emit(lefts, rights) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/editeur/differ.rb', line 50

def emit(lefts, rights)
  output = []
  for left, right in [lefts, rights].transpose     
    if not left.empty?
      output += left.map { |line| '- ' + line }
    end
    if not right.empty?
      output += right.map { |line| '+ ' + line }
    end
  end

  output
end

#subtract!(xs, ys) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/editeur/differ.rb', line 12

def subtract! xs, ys
  acc = []
  if ys.empty?
    ys = [nil]
  end

  for y in ys
    x = xs.shift
    tmp_acc = []
    while x
      if x != y
        tmp_acc << x
      else
        break
      end
      x = xs.shift
    end
    acc << tmp_acc
  end
  acc
end