Class: FrugalTimeout::SortedQueue

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Hookable
Defined in:
lib/frugal_timeout/support.rb

Overview

SortedQueue Array-like structure, providing automatic sorting of elements. When you’re accessing elements via #reject! or #first, the elements you access are sorted. There are some optimizations to ensure that elements aren’t sorted each time you call those methods.

Provides hooks: on_add, on_remove. To setup, do something like this: ‘queue.on_add { |el| puts “added #{el” }’.

Constant Summary

Constants included from Hookable

Hookable::DO_NOTHING

Instance Method Summary collapse

Methods included from Hookable

#def_hook, #def_hook_synced

Constructor Details

#initialize(storage = []) ⇒ SortedQueue

Returns a new instance of SortedQueue.



51
52
53
54
55
# File 'lib/frugal_timeout/support.rb', line 51

def initialize storage=[]
  super()
  @array, @unsorted = storage, false
  def_hook :on_add, :on_remove
end

Instance Method Details

#push(*args) ⇒ Object Also known as: <<

Raises:

  • (ArgumentError)


57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/frugal_timeout/support.rb', line 57

def push *args
  raise ArgumentError, "block can't be given for multiple elements" \
  if block_given? && args.size > 1

  args.each { |arg|
  case @array.first <=> arg
  when -1
    @array.push arg
    @unsorted = true
  when 0
    @array.unshift arg
  when 1, nil
    @array.unshift arg
    yield arg if block_given?
  end
  @on_add.call arg
  }
end

#reject!(&b) ⇒ Object



77
78
79
80
81
82
83
84
85
# File 'lib/frugal_timeout/support.rb', line 77

def reject! &b
  sort!
  @array.reject! { |el|
  if b.call el
    @on_remove.call el
    true
  end
  }
end

#reject_until_mismatch!(&b) ⇒ Object



87
88
89
90
91
92
93
94
95
# File 'lib/frugal_timeout/support.rb', line 87

def reject_until_mismatch! &b
  curSize = size
  reject! { |el|
  break unless b.call el

  true
  }
  curSize == size ? nil : self
end