summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorTobias Schmitz <tobiasschmitz2001@gmail.com>2024-05-22 17:58:06 +0200
committerGitHub <noreply@github.com>2024-05-22 15:58:06 +0000
commitb0306785d5886d5fe7047e6f5173843ecdfe7f2e (patch)
tree4be659b051ac68e73cc48b7048806bfdf5d60bc7
parent6c9bcd83ae7189154d46dda75eb3f2b4d1944501 (diff)
Add `windows` method to array (#4136)
Co-authored-by: Laurenz <laurmaedje@gmail.com>
-rw-r--r--crates/typst/src/foundations/array.rs20
-rw-r--r--tests/suite/foundations/array.typ17
2 files changed, 36 insertions, 1 deletions
diff --git a/crates/typst/src/foundations/array.rs b/crates/typst/src/foundations/array.rs
index 123dc1f5..2f65800e 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 24dad1c1..1df83fc6 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)