Cleanup indexer code

This commit is contained in:
Michael Miller 2018-11-19 19:41:51 -07:00
parent 072055d947
commit e79d8872ac

View file

@ -31,23 +31,30 @@ module Spectator
getter example_count = 0 getter example_count = 0
def [](index : Int) : Example def [](index : Int) : Example
offset = check_bounds(index)
find_nested(offset)
end
private def check_bounds(index)
if index < 0
raise IndexError.new if index < -example_count
index + example_count
else
raise IndexError.new if index >= example_count
index
end
end
private def find_nested(index)
offset = index offset = index
offset += example_count if offset < 0 child = children.each do |child|
raise IndexError.new if offset < 0 || offset >= example_count
found = children.find do |child|
count = child.example_count count = child.example_count
if offset < count break child if offset < count
true
else
offset -= count offset -= count
false
end
end
if found
found[offset]
else
raise IndexError.new
end end
# It should be impossible to get `nil` here,
# provided the bounds check and example counts are correct.
child.not_nil![offset]
end end
def finished? : Bool def finished? : Bool