Skip to content

Commit

Permalink
Add append method to array
Browse files Browse the repository at this point in the history
  • Loading branch information
JustForFun88 committed Apr 21, 2024
1 parent 0bb45b3 commit ac5e26c
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
29 changes: 29 additions & 0 deletions crates/typst/src/foundations/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -882,6 +882,35 @@ impl Array {
})
.collect()
}

/// Takes arrays and creates a new array that sequentially contains
/// all the elements of the provided arrays.
///
/// In other words, joins all provided lists onto the end of the first list.
///
/// This function is variadic, meaning that you can append multiple
/// arrays at once: `{(1, 2).append(("A", "B"), (10, 20))}` returns
/// `{(1, 2, "A", "B", 10, 20)}`.
///
#[func]
pub fn append(
mut self,
/// The real arguments (the other arguments are just for the docs, this
/// function is a bit involved, so we parse the arguments manually).
args: &mut Args,
/// The arrays to append.
#[external]
#[variadic]
others: Vec<Array>,
) -> SourceResult<Array> {
let arrays = args.all::<Array>()?;
self.0.reserve(arrays.iter().map(|x| x.0.len()).sum());
for array in arrays {
self.0.extend(array.0)
}

Ok(self)
}
}

/// A value that can be cast to bytes.
Expand Down
16 changes: 16 additions & 0 deletions tests/suite/foundations/array.typ
Original file line number Diff line number Diff line change
Expand Up @@ -492,3 +492,19 @@
--- array-unclosed ---
// Error: 3-4 unclosed delimiter
#{(}

--- array-append ---
// Test the `append` method.
#test(().append(), ())
#test((1,).append(), (1,))
#test((1,).append(()), (1,))
#test(("a", "b", "c").append((1, 2, 3)), ("a", "b", "c", 1, 2, 3))
#test(("a", "b", "c").append((1, 2, 3), (5, 6)), ("a", "b", "c", 1, 2, 3, 5, 6))

--- array-append-wrong-input-1 ---
// Error: 23-26 expected array, found string
#(true, false).append("5")

--- array-append-wrong-input-2 ---
// Error: 20-21 expected array, found integer
#("a", "b").append(1)

0 comments on commit ac5e26c

Please sign in to comment.