diff options
author | Mathias Jean Johansen <mathias@mjj.io> | 2022-05-01 13:35:07 +0200 |
---|---|---|
committer | Louis Pilfold <louis@lpil.uk> | 2022-05-04 22:08:15 +0100 |
commit | a8f009dc294d55b12f29c32afbdd3b3a43582f75 (patch) | |
tree | fa25eb2c3a0f528317ffa76598041494c208fb7b | |
parent | 4ad40c4789bcf4dea22e91a5289dd0aafd213b21 (diff) | |
download | gleam_stdlib-a8f009dc294d55b12f29c32afbdd3b3a43582f75.tar.gz gleam_stdlib-a8f009dc294d55b12f29c32afbdd3b3a43582f75.zip |
Add `capitalize` function to `String`s.
-rw-r--r-- | src/gleam/string.gleam | 21 | ||||
-rw-r--r-- | test/gleam/string_test.gleam | 30 |
2 files changed, 51 insertions, 0 deletions
diff --git a/src/gleam/string.gleam b/src/gleam/string.gleam index 3cec7d2..d574242 100644 --- a/src/gleam/string.gleam +++ b/src/gleam/string.gleam @@ -785,3 +785,24 @@ pub fn last(s: String) -> Option(String) { _ -> Some(slice(s, length(s) - 1, 1)) } } + +/// Creates a new `String` with the first grapheme in the input `String` +/// converted to uppercase and the remaining graphemes to lowercase. +/// +/// ## Examples +/// +/// ```gleam +/// > capitalize("mamouna") +/// "Mamouna" +/// ``` +/// +pub fn capitalize(s: String) -> String { + let first = + slice(s, 0, 1) + |> uppercase + let rest = + slice(s, 1, length(s)) + |> lowercase + + append(to: first, suffix: rest) +} diff --git a/test/gleam/string_test.gleam b/test/gleam/string_test.gleam index 8ad1080..14b034c 100644 --- a/test/gleam/string_test.gleam +++ b/test/gleam/string_test.gleam @@ -388,3 +388,33 @@ pub fn last_test() { |> string.last |> should.equal(Some(" ")) } + +pub fn capitalize_test() { + "" + |> string.capitalize + |> should.equal("") + + "gleam" + |> string.capitalize + |> should.equal("Gleam") + + "GLEAM" + |> string.capitalize + |> should.equal("Gleam") + + "g l e a m" + |> string.capitalize + |> should.equal("G l e a m") + + "1GLEAM" + |> string.capitalize + |> should.equal("1gleam") + + "_gLeAm1" + |> string.capitalize + |> should.equal("_gleam1") + + " gLeAm1" + |> string.capitalize + |> should.equal(" gleam1") +} |