From fb5aeaa1c1f089b88a4b0415c13903e7777839d9 Mon Sep 17 00:00:00 2001 From: Inversion Date: Tue, 22 Oct 2019 16:00:32 +0300 Subject: [PATCH] changed: strange way with recursion to simple one using % --- lib/circular_array.rb | 7 ++----- spec/circular_array_spec.rb | 8 ++++++++ 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/lib/circular_array.rb b/lib/circular_array.rb index 1735fa9..20d9914 100644 --- a/lib/circular_array.rb +++ b/lib/circular_array.rb @@ -4,11 +4,8 @@ class CircularArray < Array VERSION = '0.1.0' def [](index) - result = super + return nil if empty? - return result if result - return nil if size.zero? - - self[index - size] + super(index % size) end end diff --git a/spec/circular_array_spec.rb b/spec/circular_array_spec.rb index 022f434..f6c81e0 100644 --- a/spec/circular_array_spec.rb +++ b/spec/circular_array_spec.rb @@ -35,6 +35,14 @@ expect(circular_array[17]).to eq :c expect(circular_array[18]).to eq :a end + + it 'no recursion' do + # this will detect accidentally introduced recursion + allow(circular_array).to receive(:[]).and_call_original + expect(circular_array).to receive(:[]).exactly(2).times + expect(circular_array[1]).to eq :b + expect(circular_array[10]).to eq :b + end end context 'empty' do