From b0306785d5886d5fe7047e6f5173843ecdfe7f2e Mon Sep 17 00:00:00 2001 From: Tobias Schmitz Date: Wed, 22 May 2024 17:58:06 +0200 Subject: [PATCH] Add `windows` method to array (#4136) Co-authored-by: Laurenz --- crates/typst/src/foundations/array.rs | 20 ++++++++++++++++++++ tests/suite/foundations/array.typ | 17 ++++++++++++++++- 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/crates/typst/src/foundations/array.rs b/crates/typst/src/foundations/array.rs index 123dc1f5f..2f65800e6 100644 --- a/crates/typst/src/foundations/array.rs +++ b/crates/typst/src/foundations/array.rs @@ -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. /// diff --git a/tests/suite/foundations/array.typ b/tests/suite/foundations/array.typ index 24dad1c1f..1df83fc61 100644 --- a/tests/suite/foundations/array.typ +++ b/tests/suite/foundations/array.typ @@ -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) \ No newline at end of file +#(1, 2, 3).reduce(() => none)