diff options
| author | Gokul Soumya <gokulps15@gmail.com> | 2023-08-21 19:31:27 +0530 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2023-08-21 16:01:27 +0200 |
| commit | 5c6434d4cef8bd1bf3ad2c77f379a8b174939ab9 (patch) | |
| tree | 7b3070f2368440a6e11920e6f00b6aa458654524 /crates | |
| parent | 487fddb7cb614c649c7e0fbd61cefbd6f263fd65 (diff) | |
Add intersperse() method for arrays (#1897)
Diffstat (limited to 'crates')
| -rw-r--r-- | crates/typst/src/eval/array.rs | 24 | ||||
| -rw-r--r-- | crates/typst/src/eval/methods.rs | 1 |
2 files changed, 25 insertions, 0 deletions
diff --git a/crates/typst/src/eval/array.rs b/crates/typst/src/eval/array.rs index b98c9296..9afae865 100644 --- a/crates/typst/src/eval/array.rs +++ b/crates/typst/src/eval/array.rs @@ -287,6 +287,30 @@ impl Array { Ok(result) } + /// Returns an array with a copy of the separator value placed between + /// adjacent elements. + pub fn intersperse(&self, sep: Value) -> Array { + // TODO: Use https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.intersperse + // once it is stabilized. + let size = match self.len() { + 0 => return Array::new(), + n => (2 * n) - 1, + }; + let mut vec = EcoVec::with_capacity(size); + let mut iter = self.iter().cloned(); + + if let Some(first) = iter.next() { + vec.push(first); + } + + for value in iter { + vec.push(sep.clone()); + vec.push(value); + } + + Array(vec) + } + /// Zips the array with another array. If the two arrays are of unequal length, it will only /// zip up until the last element of the smaller array and the remaining elements will be /// ignored. The return value is an array where each element is yet another array of size 2. diff --git a/crates/typst/src/eval/methods.rs b/crates/typst/src/eval/methods.rs index a47d945b..6df504b5 100644 --- a/crates/typst/src/eval/methods.rs +++ b/crates/typst/src/eval/methods.rs @@ -154,6 +154,7 @@ pub fn call( let last = args.named("last")?; array.join(sep, last).at(span)? } + "intersperse" => array.intersperse(args.expect("separator")?).into_value(), "sorted" => array.sorted(vm, span, args.named("key")?)?.into_value(), "zip" => array.zip(args.expect("other")?).into_value(), "enumerate" => array |
