Class: Ztimer::SortedStore
- Inherits:
-
Object
- Object
- Ztimer::SortedStore
- Defined in:
- lib/ztimer/sorted_store.rb
Overview
Implements a performant sorted store for time slots, which uses binary search to optimize new items insertion and items retrievement.
Instance Method Summary collapse
- #<<(value) ⇒ Object
- #[](index) ⇒ Object
- #clear ⇒ Object
- #count ⇒ Object
- #delete(value) ⇒ Object
- #empty? ⇒ Boolean
- #first ⇒ Object
- #index_of(value, start = 0, stop = [@store.count - 1, 0].max) ⇒ Object
-
#initialize ⇒ SortedStore
constructor
A new instance of SortedStore.
- #last ⇒ Object
- #pop ⇒ Object
- #shift ⇒ Object
- #size ⇒ Object
- #to_a ⇒ Object
Constructor Details
#initialize ⇒ SortedStore
Returns a new instance of SortedStore.
7 8 9 |
# File 'lib/ztimer/sorted_store.rb', line 7 def initialize @store = [] end |
Instance Method Details
#<<(value) ⇒ Object
11 12 13 14 15 |
# File 'lib/ztimer/sorted_store.rb', line 11 def <<(value) @store.insert(position_for(value), value) self end |
#[](index) ⇒ Object
23 24 25 |
# File 'lib/ztimer/sorted_store.rb', line 23 def [](index) @store[index] end |
#clear ⇒ Object
68 69 70 |
# File 'lib/ztimer/sorted_store.rb', line 68 def clear @store.clear end |
#count ⇒ Object
56 57 58 |
# File 'lib/ztimer/sorted_store.rb', line 56 def count @store.count end |
#delete(value) ⇒ Object
17 18 19 20 21 |
# File 'lib/ztimer/sorted_store.rb', line 17 def delete(value) index = index_of(value) index.nil? ? nil : @store.delete_at(index) end |
#empty? ⇒ Boolean
64 65 66 |
# File 'lib/ztimer/sorted_store.rb', line 64 def empty? @store.empty? end |
#first ⇒ Object
27 28 29 |
# File 'lib/ztimer/sorted_store.rb', line 27 def first @store.first end |
#index_of(value, start = 0, stop = [@store.count - 1, 0].max) ⇒ Object
43 44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/ztimer/sorted_store.rb', line 43 def index_of(value, start = 0, stop = [@store.count - 1, 0].max) return nil if start > stop return value == @store[start] ? start : nil if start == stop position = ((stop + start) / 2).to_i case value <=> @store[position] when -1 then index_of(value, start, position) when 0 then position when 1 then index_of(value, position + 1, stop) end end |
#last ⇒ Object
31 32 33 |
# File 'lib/ztimer/sorted_store.rb', line 31 def last @store.last end |
#pop ⇒ Object
39 40 41 |
# File 'lib/ztimer/sorted_store.rb', line 39 def pop @store.pop end |
#shift ⇒ Object
35 36 37 |
# File 'lib/ztimer/sorted_store.rb', line 35 def shift @store.shift end |
#size ⇒ Object
60 61 62 |
# File 'lib/ztimer/sorted_store.rb', line 60 def size @store.size end |
#to_a ⇒ Object
72 73 74 |
# File 'lib/ztimer/sorted_store.rb', line 72 def to_a @store.dup end |