Queue test
This commit is contained in:
27
src/queue.cr
27
src/queue.cr
@ -1,25 +1,28 @@
|
||||
class App::CommandQueue
|
||||
class App::Queue(T)
|
||||
struct Item(T)
|
||||
def initialize(@ts : Int32, @value : T)
|
||||
end
|
||||
|
||||
getter ts
|
||||
getter value
|
||||
end
|
||||
|
||||
def initialize
|
||||
@data = [] of NamedTuple(ts: Int32, cmd: Command)
|
||||
@data = [] of Item(T)
|
||||
end
|
||||
|
||||
# Plan finishing of *command* at time *ts*
|
||||
def push(ts : Int32, cmd : Command)
|
||||
@data.push({ts: ts, cmd: cmd})
|
||||
def push(ts : Int32, value : T)
|
||||
@data.push(Item.new(ts, value))
|
||||
@data.sort! do |a, b|
|
||||
b[:ts] <=> a[:ts]
|
||||
b.ts <=> a.ts
|
||||
end
|
||||
end
|
||||
|
||||
def pop(ts : Int32)
|
||||
def pop(ts : Int32) : Item(T) | Nil
|
||||
if @data.size == 0
|
||||
return nil
|
||||
end
|
||||
last_ts = @data[-1][:ts]
|
||||
if last_ts <= ts
|
||||
return @data.pop
|
||||
else
|
||||
nil
|
||||
end
|
||||
@data[-1].ts <= ts ? @data.pop : nil
|
||||
end
|
||||
end
|
||||
|
Reference in New Issue
Block a user