Queue test

This commit is contained in:
Anton Vakhrushev 2019-09-16 18:00:53 +03:00
parent 1bec9b987c
commit 3651af523d
3 changed files with 26 additions and 13 deletions

View File

@ -9,7 +9,7 @@ format:
.PHONY: spec
spec: format
./cr spec --warnings all --error-on-warnings --time
./cr spec --warnings all --error-on-warnings
.PHONY: release
release:

View File

@ -1,5 +1,6 @@
require "spec"
require "./../src/map"
require "./../src/queue"
describe Point do
p1 = Point.new(0, 0)
@ -11,3 +12,12 @@ describe Point do
p2.distance(p1).should eq 10
end
end
describe App::Queue do
q = App::Queue(Int32).new
q.push(0, 1)
q.push(10, 2)
q.push(5, 3)
item = q.pop(50)
item.nil?.should be_falsey
end

View File

@ -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