feat(iterator): implement iterator_window (closes #1)

This commit is contained in:
Alex 2024-09-13 09:23:41 +02:00
parent c083395455
commit dc9ff1428c
Signed by: l-x
SSH key fingerprint: SHA256:MK3uQVPHEV0Oo2ry/dAqvVK3pAwegKAwSlyfgLd/yQM
2 changed files with 74 additions and 0 deletions

View file

@ -21,3 +21,33 @@ pub fn iterator_from_string(string: String) -> Iterator(String) {
iterator.unfold(from: string, with: yield) iterator.unfold(from: string, with: yield)
} }
/// Returns an iterator of sliding windows.
///
/// ## Examples
///
/// ```gleam
/// iterator.from_list([1,2,3,4,5])
/// |> iterator_window(3)
/// |> iterator.map(iterator.to_list)
/// |> iterator.to_list
/// // -> [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
/// ```
///
/// ```gleam
/// window([1, 2], 4)
/// // -> []
/// ```
///
pub fn iterator_window(i: Iterator(a), by n: Int) -> Iterator(Iterator(a)) {
let yield = fn(x: Iterator(a)) {
let chunk = x |> iterator.take(n)
case chunk |> iterator.length == n {
True -> Next(chunk, x |> iterator.drop(1))
False -> Done
}
}
iterator.unfold(from: i, with: yield)
}

View file

@ -17,3 +17,47 @@ pub fn iterator_from_string_test() {
|> string.join("") |> string.join("")
|> should.equal(string) |> should.equal(string)
} }
pub fn iterator_window_test() {
[1, 2, 3]
|> iterator.from_list
|> brilo.iterator_window(2)
|> iterator.map(iterator.to_list)
|> iterator.to_list
|> should.equal([[1, 2], [2, 3]])
}
pub fn iterator_window_empty_test() {
iterator.empty()
|> brilo.iterator_window(2)
|> iterator.map(iterator.to_list)
|> iterator.to_list
|> should.equal([])
}
pub fn iterator_window_one_size_test() {
[1, 2, 3, 4, 5]
|> iterator.from_list
|> brilo.iterator_window(1)
|> iterator.map(iterator.to_list)
|> iterator.to_list
|> should.equal([[1], [2], [3], [4], [5]])
}
pub fn iterator_window_full_size_test() {
[1, 2, 3, 4, 5]
|> iterator.from_list
|> brilo.iterator_window(5)
|> iterator.map(iterator.to_list)
|> iterator.to_list
|> should.equal([[1, 2, 3, 4, 5]])
}
pub fn iterator_window_over_size_test() {
[1, 2, 3, 4, 5]
|> iterator.from_list
|> brilo.iterator_window(6)
|> iterator.map(iterator.to_list)
|> iterator.to_list
|> should.equal([])
}