gleam-lang / gleam-lang/stdlib
More string trimming capabilities
- Dominant language
- Gleam
- Stars
- 710
- Forks
- 225
- Avg merge
- 5h 52m
- Merged PRs (30d)
- 3
Description
The existing `string.trim`, `string.trim_left` and `string.trim_right` functions currently only trim whitespace.
Could we add equivalent trimming functions that take the codepoints to be trimmed as an input, similar to Erlang's [`string.trim/3`](https://www.erlang.org/doc/man/string#trim-3)?
E.g.
```gleam
import gleam/list
/// Removes all occurrences of the specified codepoints from the start and
/// end of a `String`.
///
pub fn trim_codepoints(s: String, codepoints: List(UtfCodepoint)) -> String {
string_trim(s, Both, codepoints_to_ints(codepoints))
}
/// Removes all occurrences of the specified codepoints from the start of a
/// `String`.
///
pub fn trim_codepoints_left(s: String, codepoints: List(UtfCodepoint)) -> String {
string_trim(s, Leading, codepoints_to_ints(codepoints))
}
/// Removes all occurrences of the specified codepoints from the end of a
/// `String`.
///
pub fn trim_codepoints_right(
s: String,
codepoints: List(UtfCodepoint),
) -> String {
string_trim(s, Trailing, codepoints_to_ints(codepoints))
}
fn codepoints_to_ints(codepoints: List(UtfCodepoint)) {
codepoints
|> list.map(string.utf_codepoint_to_int)
}
type Direction {
Leading
Trailing
Both
}
@target(erlang)
@external(erlang, "string", "trim")
fn string_trim(a: String, b: Direction, c: List(Int)) -> String
```
There are other ways to slice this, such as taking a `String` as the final parameter and using its codepoints as the ones to trim, rather than a `List(UtfCodepoint)`.
I haven't looked into what the JavaScript implementation would be, but can do so.
On a related note, my understanding is that the existing methods with the words "left" and "right" in them assume left-to-right reading order, which doesn't hold for all languages (e.g. Arabic, Hebrew). Could consider using "start" and "end" instead, or adding these as aliases.
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.