From 863bf369b8a8b1eeb58c6fb8fc81e093b08bbda7 Mon Sep 17 00:00:00 2001 From: Luka Vandervelden Date: Fri, 10 Jan 2020 17:20:10 +0100 Subject: [PATCH] #reverse_each, #reverse_each_with_index added. --- spec/test.cr | 23 ++++++++++++++++++++--- src/dodb.cr | 22 ++++++++++++++++++++++ 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/spec/test.cr b/spec/test.cr index 3ddc086..d50f240 100644 --- a/spec/test.cr +++ b/spec/test.cr @@ -30,11 +30,12 @@ class Ship # and can easily be extended. class_getter kisaragi = Ship.new("Kisaragi", "Mutsuki") - class_getter mutsuki = Ship.new("Mutsuki", "Mutsuki", tags: ["name ship"]) + class_getter mutsuki = Ship.new("Mutsuki", "Mutsuki", tags: ["name ship"]) + class_getter yayoi = Ship.new("Yayoi", "Mutsuki") class_getter destroyers = [ - @@kisaragi, @@mutsuki, - Ship.new("Yayoi", "Mutsuki"), + @@kisaragi, + @@yayoi, Ship.new("Uzuki", "Mutsuki"), Ship.new("Satsuki", "Mutsuki"), @@ -157,6 +158,22 @@ describe "DODB::DataBase" do db1.to_a.size.should eq(2) end + + it "iterates in normal and reversed order" do + db = DODB::SpecDataBase.new + + Ship.all_ships.each do |ship| + db << ship + end + + db.each_with_index do |item, index| + item.should eq Ship.all_ships[index] + end + + db.reverse_each_with_index do |item, index| + item.should eq Ship.all_ships.reverse[index] + end + end end describe "indices" do diff --git a/src/dodb.cr b/src/dodb.cr index 0004e91..33a73c0 100644 --- a/src/dodb.cr +++ b/src/dodb.cr @@ -206,6 +206,28 @@ class DODB::DataBase(V) end end + def reverse_each_with_index + (last_index..0).each do |key| + full_path = file_path key + + next unless File.exists? full_path + + begin + # FIXME: Only intercept JSON parsing errors. + item = read full_path + rescue + next + end + + yield item, key + end + end + def reverse_each + reverse_each_with_index do |item, index| + yield item + end + end + ## # CAUTION: Very slow. Try not to use. def to_a