Class: Geom2D::Utils::SortedList

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/geom2d/utils/sorted_list.rb

Overview

A list that keeps its items sorted. Currently only used by Geom2D::Algorithms::PolygonOperation and therefore with special methods for the latter.

Instance Method Summary collapse

Constructor Details

#initialize(comparator = nil, &block) ⇒ SortedList

Creates a new SortedList using the comparator or the given block as compare function.

The comparator has to respond to call(a, b) where a is the value to be inserted and b is the value to which it is compared. The return value should be true if the value a should be inserted before b, i.e. at the position of b.



25
26
27
28
# File 'lib/geom2d/utils/sorted_list.rb', line 25

def initialize(comparator = nil, &block)
  @list = []
  @comparator = comparator || block
end

Instance Method Details

#clearObject

Clears the list.



70
71
72
# File 'lib/geom2d/utils/sorted_list.rb', line 70

def clear
  @list.clear
end

#delete(value) ⇒ Object

Deletes the given value and returns the previous and next values.



62
63
64
65
66
67
# File 'lib/geom2d/utils/sorted_list.rb', line 62

def delete(value)
  i = @list.index(value)
  result = [(i == 0 ? nil : @list[i - 1]), @list[i + 1]]
  @list.delete_at(i)
  result
end

#each(&block) ⇒ Object

Yields each value in sorted order.

If no block is given, an enumerator is returned.



43
44
45
# File 'lib/geom2d/utils/sorted_list.rb', line 43

def each(&block) # :yield: value
  @list.each(&block)
end

#empty?Boolean

Returns true if the list is empty?

Returns:

  • (Boolean)


31
32
33
# File 'lib/geom2d/utils/sorted_list.rb', line 31

def empty?
  @list.empty?
end

#insert(value) ⇒ Object

Inserts a new value into the list (at a position decided by the compare function) and returns the previous-previous, previous and next values.



55
56
57
58
59
# File 'lib/geom2d/utils/sorted_list.rb', line 55

def insert(value)
  i = @list.bsearch_index {|el| @comparator.call(value, el) } || @list.size
  @list.insert(i, value)
  [(i <= 1 ? nil : @list[i - 2]), (i == 0 ? nil : @list[i - 1]), @list[i + 1]]
end

#inspectObject

:nodoc:



79
80
81
# File 'lib/geom2d/utils/sorted_list.rb', line 79

def inspect # :nodoc:
  "#<#{self.class.name}:0x#{object_id.to_s(16).rjust(0.size * 2, '0')} #{to_a}>"
end

#lastObject

Returns the last value in the list.



36
37
38
# File 'lib/geom2d/utils/sorted_list.rb', line 36

def last
  @list.last
end

#popObject

Removes the top value from the list and returns it.



75
76
77
# File 'lib/geom2d/utils/sorted_list.rb', line 75

def pop
  @list.pop
end

#push(value) ⇒ Object

Inserts the value and returns self.



48
49
50
51
# File 'lib/geom2d/utils/sorted_list.rb', line 48

def push(value)
  insert(value)
  self
end