Class: Ztimer::SortedStore

Inherits:
Object
  • Object
show all
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

Constructor Details

#initializeSortedStore

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

#clearObject



68
69
70
# File 'lib/ztimer/sorted_store.rb', line 68

def clear
  @store.clear
end

#countObject



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

Returns:

  • (Boolean)


64
65
66
# File 'lib/ztimer/sorted_store.rb', line 64

def empty?
  @store.empty?
end

#firstObject



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

#lastObject



31
32
33
# File 'lib/ztimer/sorted_store.rb', line 31

def last
  @store.last
end

#popObject



39
40
41
# File 'lib/ztimer/sorted_store.rb', line 39

def pop
  @store.pop
end

#shiftObject



35
36
37
# File 'lib/ztimer/sorted_store.rb', line 35

def shift
  @store.shift
end

#sizeObject



60
61
62
# File 'lib/ztimer/sorted_store.rb', line 60

def size
  @store.size
end

#to_aObject



72
73
74
# File 'lib/ztimer/sorted_store.rb', line 72

def to_a
  @store.dup
end