From 3651af523d0d22a1f5df4a67f8a7f5a672dd6625 Mon Sep 17 00:00:00 2001 From: Anton Vakhrushev Date: Mon, 16 Sep 2019 18:00:53 +0300 Subject: [PATCH] Queue test --- Makefile | 2 +- spec/village_spec.cr | 10 ++++++++++ src/queue.cr | 27 +++++++++++++++------------ 3 files changed, 26 insertions(+), 13 deletions(-) diff --git a/Makefile b/Makefile index 2d41ed0..bff4481 100644 --- a/Makefile +++ b/Makefile @@ -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: diff --git a/spec/village_spec.cr b/spec/village_spec.cr index b53eefc..6b8ce09 100644 --- a/spec/village_spec.cr +++ b/spec/village_spec.cr @@ -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 diff --git a/src/queue.cr b/src/queue.cr index 61785a1..231cca7 100644 --- a/src/queue.cr +++ b/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