lib/range_compacter.rb in range_compacter-1.0.0 vs lib/range_compacter.rb in range_compacter-1.0.1
- old
+ new
@@ -8,34 +8,31 @@
@items = items
end
# Main logic
def compact(target_range)
- used = []
+ result = []
- items_in_range = @items.select do |item|
+ target_items = @items.select do |item|
item.cover?(target_range.begin) || target_range.cover?(item.begin)
end.sort_by(&:begin)
- items_in_range.each_with_object([]) do |item, result|
- next if used.include? item
+ target_items.each_with_index do |item, idx|
+ next if result.flatten.include?(item)
if item.begin <= target_range.begin && item.end >= target_range.end
result << item
- used << item
else
- item_to_compact = items_in_range.find do |i|
- item.end <= i.begin && !used.include?(i)
+ item_to_compact = target_items[idx..].bsearch do |i|
+ item.end <= i.begin && !result.flatten.include?(i)
end
if item_to_compact
result << [item, item_to_compact]
- used << item_to_compact
else
result << item
end
- used << item
end
- result
end
+ result
end
end
end