aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMarcin Puc <5671049+tranzystorek-io@users.noreply.github.com>2021-03-08 23:50:29 +0100
committerGitHub <noreply@github.com>2021-03-08 23:50:29 +0100
commit926a0c57cb27bc6a8ee3d4f9fd73fe430ddcf787 (patch)
treee946e869650654689bf65b9c7c1e07d2419b3907
parentd86237c4c07426d5f5df8fefd8f3e046b35ef4a4 (diff)
downloadgleam_stdlib-926a0c57cb27bc6a8ee3d4f9fd73fe430ddcf787.tar.gz
gleam_stdlib-926a0c57cb27bc6a8ee3d4f9fd73fe430ddcf787.zip
Add iterator.index (#169)
-rw-r--r--src/gleam/iterator.gleam26
-rw-r--r--test/gleam/iterator_test.gleam7
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)