mirror of
https://github.com/typst/typst
synced 2025-07-11 22:52:53 +08:00
Add default
argument for str.first
and str.last
(#6554)
Co-authored-by: Laurenz <laurmaedje@gmail.com>
This commit is contained in:
parent
9e6adb6f45
commit
1dc4c248d1
@ -179,24 +179,40 @@ impl Str {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Extracts the first grapheme cluster of the string.
|
/// Extracts the first grapheme cluster of the string.
|
||||||
/// Fails with an error if the string is empty.
|
///
|
||||||
|
/// Returns the provided default value if the string is empty or fails with
|
||||||
|
/// an error if no default value was specified.
|
||||||
#[func]
|
#[func]
|
||||||
pub fn first(&self) -> StrResult<Str> {
|
pub fn first(
|
||||||
|
&self,
|
||||||
|
/// A default value to return if the string is empty.
|
||||||
|
#[named]
|
||||||
|
default: Option<Str>,
|
||||||
|
) -> StrResult<Str> {
|
||||||
self.0
|
self.0
|
||||||
.graphemes(true)
|
.graphemes(true)
|
||||||
.next()
|
.next()
|
||||||
.map(Into::into)
|
.map(Into::into)
|
||||||
|
.or(default)
|
||||||
.ok_or_else(string_is_empty)
|
.ok_or_else(string_is_empty)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Extracts the last grapheme cluster of the string.
|
/// Extracts the last grapheme cluster of the string.
|
||||||
/// Fails with an error if the string is empty.
|
///
|
||||||
|
/// Returns the provided default value if the string is empty or fails with
|
||||||
|
/// an error if no default value was specified.
|
||||||
#[func]
|
#[func]
|
||||||
pub fn last(&self) -> StrResult<Str> {
|
pub fn last(
|
||||||
|
&self,
|
||||||
|
/// A default value to return if the string is empty.
|
||||||
|
#[named]
|
||||||
|
default: Option<Str>,
|
||||||
|
) -> StrResult<Str> {
|
||||||
self.0
|
self.0
|
||||||
.graphemes(true)
|
.graphemes(true)
|
||||||
.next_back()
|
.next_back()
|
||||||
.map(Into::into)
|
.map(Into::into)
|
||||||
|
.or(default)
|
||||||
.ok_or_else(string_is_empty)
|
.ok_or_else(string_is_empty)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -103,6 +103,10 @@
|
|||||||
#test("Hello".last(), "o")
|
#test("Hello".last(), "o")
|
||||||
#test("🏳️🌈A🏳️⚧️".first(), "🏳️🌈")
|
#test("🏳️🌈A🏳️⚧️".first(), "🏳️🌈")
|
||||||
#test("🏳️🌈A🏳️⚧️".last(), "🏳️⚧️")
|
#test("🏳️🌈A🏳️⚧️".last(), "🏳️⚧️")
|
||||||
|
#test("hey".first(default: "d"), "h")
|
||||||
|
#test("".first(default: "d"), "d")
|
||||||
|
#test("hey".last(default: "d"), "y")
|
||||||
|
#test("".last(default: "d"), "d")
|
||||||
|
|
||||||
--- string-first-empty ---
|
--- string-first-empty ---
|
||||||
// Error: 2-12 string is empty
|
// Error: 2-12 string is empty
|
||||||
|
Loading…
x
Reference in New Issue
Block a user