aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRichard Viney <richard.viney@gmail.com>2024-10-07 17:40:31 +1300
committerLouis Pilfold <louis@lpil.uk>2024-10-08 12:16:44 +0100
commit0a087d5d80b803e70909848f5b7b28ce2b5df4fc (patch)
treee67d3d529e565d89b76e7cfe76caf72c684e7102
parent3b966c2715593d07bfa1208879aa5ccbdb648dbc (diff)
downloadgleam_stdlib-0a087d5d80b803e70909848f5b7b28ce2b5df4fc.tar.gz
gleam_stdlib-0a087d5d80b803e70909848f5b7b28ce2b5df4fc.zip
Optimise string.repeat
-rw-r--r--CHANGELOG.md3
-rw-r--r--src/gleam/string.gleam12
2 files changed, 9 insertions, 6 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 03c850f..c48880a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,8 +5,7 @@
- The `bit_array` module gains the `compare` function.
- The `float` modeule gains the `to_precision` function.
- The `try_fold` function in the `iterator` module is now tail recursive.
-- The performance of many functions in the `string` module on the JavaScript
- target has been improved.
+- The performance of many functions in the `string` module has been improved.
## v0.40.0 - 2024-08-19
diff --git a/src/gleam/string.gleam b/src/gleam/string.gleam
index e530c8f..0906481 100644
--- a/src/gleam/string.gleam
+++ b/src/gleam/string.gleam
@@ -438,10 +438,14 @@ pub fn concat(strings: List(String)) -> String {
/// ```
///
pub fn repeat(string: String, times times: Int) -> String {
- iterator.repeat(string)
- |> iterator.take(times)
- |> iterator.to_list
- |> concat
+ do_repeat(string, times, "")
+}
+
+fn do_repeat(string: String, times: Int, acc: String) -> String {
+ case times <= 0 {
+ True -> acc
+ False -> do_repeat(string, times - 1, acc <> string)
+ }
}
/// Joins many `String`s together with a given separator.