Skip to content

Commit b5678c0

Browse files
committed
changed: strange way with recursion to simple one using %
1 parent eb5c26c commit b5678c0

File tree

2 files changed

+8
-7
lines changed

2 files changed

+8
-7
lines changed

lib/circular_array.rb

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,7 @@ class CircularArray < Array
44
VERSION = '0.1.0'
55

66
def [](index)
7-
result = super
8-
9-
return result if result
10-
return nil if size.zero?
11-
12-
self[index - size]
7+
return nil if empty?
8+
super(index % size)
139
end
1410
end

spec/circular_array_spec.rb

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,15 @@
1111

1212
it 'behaives like array' do
1313
expect(circular_array).to be_kind_of Array
14-
14+
15+
# this will detect accidentally introduced recursion
16+
allow(circular_array).to receive(:[]).and_call_original
17+
expect(circular_array).to receive(:[]).exactly(4).times
18+
1519
expect(circular_array[0]).to eq :a
1620
expect(circular_array[1]).to eq :b
1721
expect(circular_array[2]).to eq :c
22+
expect(circular_array[10]).to eq :b
1823
end
1924

2025
it 'endless' do

0 commit comments

Comments
 (0)