diff options
-rw-r--r-- | src/gleam/iterator.gleam | 26 | ||||
-rw-r--r-- | test/gleam/iterator_test.gleam | 7 |
2 files changed, 33 insertions, 0 deletions
diff --git a/src/gleam/iterator.gleam b/src/gleam/iterator.gleam index f441859..9146833 100644 --- a/src/gleam/iterator.gleam +++ b/src/gleam/iterator.gleam @@ -495,6 +495,32 @@ pub fn find( } } +fn do_index( + continuation: fn() -> Action(element), + next: Int, +) -> fn() -> Action(tuple(Int, element)) { + fn() { + case continuation() { + Continue(e, continuation) -> + Continue(tuple(next, e), do_index(continuation, next + 1)) + Stop -> Stop + } + } +} + +/// Wraps values yielded from an iterator with indices, starting from 0. +/// +/// ## Examples +/// +/// > from_list(["a", "b", "c"]) |> index |> to_list +/// [tuple(0, "a"), tuple(1, "b"), tuple(2, "c")] +/// +pub fn index(over iterator: Iterator(element)) -> Iterator(tuple(Int, element)) { + iterator.continuation + |> do_index(0) + |> Iterator +} + /// Creates an iterator that inifinitely applies a function to a value. /// /// ## Examples diff --git a/test/gleam/iterator_test.gleam b/test/gleam/iterator_test.gleam index af38508..098b1b9 100644 --- a/test/gleam/iterator_test.gleam +++ b/test/gleam/iterator_test.gleam @@ -251,6 +251,13 @@ pub fn find_test() { |> should.equal(Ok(Cat(id: 10))) } +pub fn index_test() { + iterator.from_list(["a", "b", "c"]) + |> iterator.index + |> iterator.to_list + |> should.equal([tuple(0, "a"), tuple(1, "b"), tuple(2, "c")]) +} + pub fn iterate_test() { fn(x) { x * 3 } |> iterator.iterate(from: 1) |