Does anyone have a guide for how to create a custom iterator?
For example, I want to be able to return an something Iterable from a function that is trying to search over something. I feel like I’m missing a Crystal idiom for how to string iterators together.
Benchmarking something like this, were I create a struct that includes Iterator, vs something that just returns an array, the array return is much faster.
# This is contrived! I know there are faster ways to sum this. class DataHolder getter data def initialize(@data : Array(Int32)) end def find(query : Int32) # I want to return an iterator of values that matched in @data IterFind.new(self, query, 0) end end struct IterFind include Iterator(Int32) def initialize(@inner : DataHolder, @query : Int32, @offset : Int32) end def next while @offset < @inner.data.size data = @inner.data[@offset] @offset += 1 if data == @query return data end end stop end end data_holder = DataHolder.new([2, 3, 4, 2, 2, 4, 5, 2]) p data_holder.find(2).sum
The real life code I’m trying to optimize is: https://github.com/sstadick/lapper.cr/blob/00e11d2717e4a24e8cf1c5ec80afdcc8a2105c29/src/lapper.cr#L173