Class: Astel::Rewriter::EditIndex

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/astel/rewriter.rb

Constant Summary collapse

SPLIT_THRESHOLD =
256

Instance Method Summary collapse

Constructor Details

#initializeEditIndex

Returns a new instance of EditIndex.



27
28
29
# File 'lib/astel/rewriter.rb', line 27

def initialize
  @blocks = []
end

Instance Method Details

#add(edit) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/astel/rewriter.rb', line 31

def add(edit)
  if @blocks.empty?
    @blocks << [edit]
    return
  end

  block_index = block_index_for(edit)
  block = @blocks.fetch(block_index)
  edit_index = block.bsearch_index { |existing| ordered_after?(existing, edit) } || block.length
  following = block[edit_index] || @blocks[block_index + 1]&.first
  return following if following && yield(following)

  preceding = if edit_index.positive?
                block[edit_index - 1]
              elsif block_index.positive?
                @blocks[block_index - 1].last
              end
  return preceding if preceding && yield(preceding)

  block.insert(edit_index, edit)
  split(block_index, block) if block.length > SPLIT_THRESHOLD
  nil
end

#eachObject



55
56
57
58
59
60
61
# File 'lib/astel/rewriter.rb', line 55

def each
  return enum_for(__method__) unless block_given?

  @blocks.each do |block|
    block.each { |edit| yield edit }
  end
end