Skip to content

Commit b0afb8f

Browse files
richard-vineylpil
authored andcommitted
Optimise string trimming on JavaScript
1 parent 8349133 commit b0afb8f

File tree

3 files changed

+30
-5
lines changed

3 files changed

+30
-5
lines changed

CHANGELOG.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
# Changelog
22

3+
## Unreleased
4+
5+
- The performance of `string.trim`, `string.trim_start`, and `string.trim_end`
6+
has been improved on JavaScript.
7+
38
## v0.44.0 - 2024-11-25
49

510
- The `gleam/queue` module has been deprecated in favour of the `gleam_deque`

src/gleam_stdlib.mjs

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -302,19 +302,22 @@ const unicode_whitespaces = [
302302
"\u2029", // Paragraph separator
303303
].join("");
304304

305-
const left_trim_regex = new RegExp(`^([${unicode_whitespaces}]*)`, "g");
306-
const right_trim_regex = new RegExp(`([${unicode_whitespaces}]*)$`, "g");
305+
const trim_start_regex = new RegExp(`^[${unicode_whitespaces}]*`);
306+
const trim_end_regex = new RegExp(`[${unicode_whitespaces}]*$`);
307+
const trim_regex = new RegExp(
308+
`^[${unicode_whitespaces}]*(.*?)[${unicode_whitespaces}]*$`
309+
);
307310

308311
export function trim(string) {
309-
return trim_start(trim_end(string));
312+
return string.match(trim_regex)[1];
310313
}
311314

312315
export function trim_start(string) {
313-
return string.replace(left_trim_regex, "");
316+
return string.replace(trim_start_regex, "");
314317
}
315318

316319
export function trim_end(string) {
317-
return string.replace(right_trim_regex, "");
320+
return string.replace(trim_end_regex, "");
318321
}
319322

320323
export function bit_array_from_string(string) {

test/gleam/string_test.gleam

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,23 @@ pub fn trim_end_test() {
179179
|> should.equal(" hats")
180180
}
181181

182+
pub fn trim_whole_string_test() {
183+
let s =
184+
"\u{0020}\u{0009}\u{000A}\u{000B}\u{000C}\u{000D}\u{0085}\u{2028}\u{2029}"
185+
186+
s
187+
|> string.trim_start
188+
|> should.equal("")
189+
190+
s
191+
|> string.trim_end
192+
|> should.equal("")
193+
194+
s
195+
|> string.trim
196+
|> should.equal("")
197+
}
198+
182199
// unicode whitespaces
183200
pub fn trim_horizontal_tab_test() {
184201
"hats\u{0009}"

0 commit comments

Comments
 (0)