Add windows method to array (#4136)

Co-authored-by: Laurenz <laurmaedje@gmail.com>
This commit is contained in:
Tobias Schmitz 2024-05-22 17:58:06 +02:00 committed by GitHub
parent 6c9bcd83ae
commit b0306785d5
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 36 additions and 1 deletions

View File

@ -790,6 +790,26 @@ impl Array {
}
}
/// Returns sliding windows of `window-size` elements over an array.
///
/// If the array length is less than `window-size`, this will return an empty array.
///
/// ```example
/// #let array = (1, 2, 3, 4, 5, 6, 7, 8)
/// #array.windows(5)
/// ```
#[func]
pub fn windows(
self,
/// How many elements each window will contain.
window_size: NonZeroUsize,
) -> Array {
self.0
.windows(window_size.get())
.map(|window| Array::from(window).into_value())
.collect()
}
/// Return a sorted version of this array, optionally by a given key
/// function. The sorting algorithm used is stable.
///

View File

@ -328,6 +328,21 @@
// Error: 19-21 number must be positive
#(1, 2, 3).chunks(-5)
--- array-windows ---
// Test the `windows` method.
#test(().windows(5), ())
#test((1, 2, 3).windows(5), ())
#test((1, 2, 3, 4, 5).windows(3), ((1, 2, 3), (2, 3, 4), (3, 4, 5)))
#test((1, 2, 3, 4, 5, 6, 7, 8).windows(5), ((1, 2, 3, 4, 5), (2, 3, 4, 5, 6), (3, 4, 5, 6, 7), (4, 5, 6, 7, 8)))
--- array-windows-size-zero ---
// Error: 20-21 number must be positive
#(1, 2, 3).windows(0)
--- array-windows-size-negative ---
// Error: 20-22 number must be positive
#(1, 2, 3).windows(-5)
--- array-sorted ---
// Test the `sorted` method.
#test(().sorted(), ())
@ -514,4 +529,4 @@
--- array-reduce-unexpected-argument ---
// Error: 19-21 unexpected argument
#(1, 2, 3).reduce(() => none)
#(1, 2, 3).reduce(() => none)