feat(iterator): implement iterator_window_by_2 (closes #2)

This commit is contained in:
Alex 2024-09-13 09:45:32 +02:00
parent dc9ff1428c
commit 46ed11c1de
Signed by: l-x
SSH key fingerprint: SHA256:MK3uQVPHEV0Oo2ry/dAqvVK3pAwegKAwSlyfgLd/yQM
2 changed files with 53 additions and 2 deletions

View file

@ -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))
}

View file

@ -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([])
}