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 .PHONY: spec
spec: format spec: format
./cr spec --warnings all --error-on-warnings --time ./cr spec --warnings all --error-on-warnings
.PHONY: release .PHONY: release
release: release:

View File

@ -1,5 +1,6 @@
require "spec" require "spec"
require "./../src/map" require "./../src/map"
require "./../src/queue"
describe Point do describe Point do
p1 = Point.new(0, 0) p1 = Point.new(0, 0)
@ -11,3 +12,12 @@ describe Point do
p2.distance(p1).should eq 10 p2.distance(p1).should eq 10
end end
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 def initialize
@data = [] of NamedTuple(ts: Int32, cmd: Command) @data = [] of Item(T)
end end
# Plan finishing of *command* at time *ts* # Plan finishing of *command* at time *ts*
def push(ts : Int32, cmd : Command) def push(ts : Int32, value : T)
@data.push({ts: ts, cmd: cmd}) @data.push(Item.new(ts, value))
@data.sort! do |a, b| @data.sort! do |a, b|
b[:ts] <=> a[:ts] b.ts <=> a.ts
end end
end end
def pop(ts : Int32) def pop(ts : Int32) : Item(T) | Nil
if @data.size == 0 if @data.size == 0
return nil return nil
end end
last_ts = @data[-1][:ts] @data[-1].ts <= ts ? @data.pop : nil
if last_ts <= ts
return @data.pop
else
nil
end
end end
end end