From 6dc3a6d2f7c67dc5103e2700c4a1671263f50ea0 Mon Sep 17 00:00:00 2001 From: Luka Vandervelden Date: Mon, 13 Jan 2020 13:48:24 +0100 Subject: [PATCH] Fixes reversed: true. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Hey crystal, why don’t you have reversed ranges? --- spec/test.cr | 6 +++++- src/dodb.cr | 23 +++++++++++++++-------- 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/spec/test.cr b/spec/test.cr index 8cb48e5..8613e78 100644 --- a/spec/test.cr +++ b/spec/test.cr @@ -166,13 +166,17 @@ describe "DODB::DataBase" do db << ship end + # The two #each test iteration. db.each_with_index do |item, index| item.should eq Ship.all_ships[index] end db.each_with_index(reversed: true) do |item, index| - item.should eq Ship.all_ships.reverse[index] + item.should eq Ship.all_ships[index] end + + # Actual reversal is tested here. + db.to_a(reversed: true).should eq db.to_a.reverse end it "respects the provided offsets if any" do diff --git a/src/dodb.cr b/src/dodb.cr index 8efb3ab..8ec346e 100644 --- a/src/dodb.cr +++ b/src/dodb.cr @@ -179,18 +179,25 @@ class DODB::DataBase(V) end private def each_key(reversed = false) - range = if reversed - (last_index..0) - else - (0..last_index) - end + start = 0 + _end = last_index + step = 1 - range.each do |key| + if reversed + start = _end + _end = 0 + step = -1 + end + + key = start + while step == 1 ? key <= _end : key >= _end full_path = file_path key - next unless File.exists? full_path + if File.exists? full_path + yield key, full_path + end - yield key, full_path + key = key + step end end