From 46ed11c1de1d9cf657d0bbc3ef4ddcc11be5d51a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20W=C3=BChr?= Date: Fri, 13 Sep 2024 09:45:32 +0200 Subject: [PATCH] feat(iterator): implement `iterator_window_by_2` (closes #2) --- src/brilo.gleam | 20 ++++++++++++++++++++ test/brilo_test.gleam | 35 +++++++++++++++++++++++++++++++++-- 2 files changed, 53 insertions(+), 2 deletions(-) diff --git a/src/brilo.gleam b/src/brilo.gleam index 5aa0616..233265a 100644 --- a/src/brilo.gleam +++ b/src/brilo.gleam @@ -51,3 +51,23 @@ pub fn iterator_window(i: Iterator(a), by n: Int) -> Iterator(Iterator(a)) { iterator.unfold(from: i, with: yield) } + +/// Returns an iterator of tuples containing two contiguous elements. +/// +/// ## Examples +/// +/// ```gleam +/// iterator_window_by_2([1,2,3,4]) +/// |> iterator.to_list +/// // -> [#(1, 2), #(2, 3), #(3, 4)] +/// ``` +/// +/// ```gleam +/// iterator_window_by_2([1]) +/// |> iterator.to_list +/// // -> [] +/// ``` +/// +pub fn iterator_window_by_2(i: Iterator(a)) -> Iterator(#(a, a)) { + iterator.zip(i, iterator.drop(i, 1)) +} diff --git a/test/brilo_test.gleam b/test/brilo_test.gleam index 4604980..ae9fb40 100644 --- a/test/brilo_test.gleam +++ b/test/brilo_test.gleam @@ -19,12 +19,12 @@ pub fn iterator_from_string_test() { } pub fn iterator_window_test() { - [1, 2, 3] + [1, 2, 3, 4, 5] |> iterator.from_list |> brilo.iterator_window(2) |> iterator.map(iterator.to_list) |> iterator.to_list - |> should.equal([[1, 2], [2, 3]]) + |> should.equal([[1, 2], [2, 3], [3, 4], [4, 5]]) } pub fn iterator_window_empty_test() { @@ -61,3 +61,34 @@ pub fn iterator_window_over_size_test() { |> iterator.to_list |> should.equal([]) } + +pub fn iterator_window_by_2_test() { + [1, 2, 3, 4, 5] + |> iterator.from_list + |> brilo.iterator_window_by_2 + |> iterator.to_list + |> should.equal([#(1, 2), #(2, 3), #(3, 4), #(4, 5)]) +} + +pub fn iterator_window_by_2_empty_test() { + iterator.empty() + |> brilo.iterator_window_by_2 + |> iterator.to_list + |> should.equal([]) +} + +pub fn iterator_window_by_2_full_size_test() { + [1, 2] + |> iterator.from_list + |> brilo.iterator_window_by_2 + |> iterator.to_list + |> should.equal([#(1, 2)]) +} + +pub fn iterator_window_by_2_over_size_test() { + [1] + |> iterator.from_list + |> brilo.iterator_window_by_2 + |> iterator.to_list + |> should.equal([]) +}