feat(iterator): implement iterator_window
(closes #1)
This commit is contained in:
parent
c083395455
commit
dc9ff1428c
2 changed files with 74 additions and 0 deletions
|
@ -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)
|
||||||
|
}
|
||||||
|
|
|
@ -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([])
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in a new issue