diff options
author | Richard Viney <richard.viney@gmail.com> | 2024-10-07 10:57:50 +1300 |
---|---|---|
committer | Louis Pilfold <louis@lpil.uk> | 2024-10-09 17:43:58 +0100 |
commit | 4c3ea2086cf7662f79628f26abff15307ff5bce9 (patch) | |
tree | 43d91c59faa8ab4d97e416eff374a25dc26b9603 /src/gleam_stdlib.mjs | |
parent | 0a087d5d80b803e70909848f5b7b28ce2b5df4fc (diff) | |
download | gleam_stdlib-4c3ea2086cf7662f79628f26abff15307ff5bce9.tar.gz gleam_stdlib-4c3ea2086cf7662f79628f26abff15307ff5bce9.zip |
Optimise string.pad_left, string.pad_right. Optimise string.slice on JS.
Diffstat (limited to 'src/gleam_stdlib.mjs')
-rw-r--r-- | src/gleam_stdlib.mjs | 28 |
1 files changed, 28 insertions, 0 deletions
diff --git a/src/gleam_stdlib.mjs b/src/gleam_stdlib.mjs index 1aa4753..58a032e 100644 --- a/src/gleam_stdlib.mjs +++ b/src/gleam_stdlib.mjs @@ -223,6 +223,34 @@ export function length(data) { return data.length; } +export function string_slice(string, idx, len) { + if (len <= 0 || idx >= string.length) { + return ""; + } + + const iterator = graphemes_iterator(string); + if (iterator) { + while (idx-- > 0) { + iterator.next(); + } + + let result = ""; + + while (len-- > 0) { + const v = iterator.next().value; + if (v === undefined) { + break; + } + + result += v.segment; + } + + return result; + } else { + return string.match(/./gsu).slice(idx, idx + len).join(""); + } +} + export function crop_string(string, substring) { return string.substring(string.indexOf(substring)); } |