Elixir's String.capitalize/2
function "converts the first character in the given string to uppercase and the remainder to lowercase". Would it not be more intuitive to capitalize the first character and leave the remaining characters unchanged? Maybe there is some reasoning I am missing?
The current implementation results in the local ATM
-> The local Atm
, forgotten PIN
-> Forgotten Pin
etc.
Here is a solution that does not require calling the undocumented implementation specific String.Casing
.
with <<c :: utf8, rest :: binary>> <- "the local ATM",
do: String.upcase(<<c>>) <> rest
#⇒ "The local ATM"
The above works with unicode characters as well (both composed and decomposed):
with <<c :: utf8, rest :: binary>> <- "über BVG",
do: String.upcase(<<c>>) <> rest
#⇒ "Über BVG"
This is elixir api that get's called for capitalisation.
def capitalize(string, mode) when is_binary(string) do
{char, rest} = String.Casing.titlecase_once(string, mode)
char <> downcase(rest, mode)
end
If we want to fulfil your requirement which is to capitalise only first letter than we could perform something like this. Here we only removed extra down casing call so we have only made this code more robust when it comes to performance.
def capitalize_only_first(string, mode) when is_binary(string) do
{char, rest} = String.Casing.titlecase_once(string, mode)
char <> rest
end
Second implementation is better from performance point of view. So, I believe only reason to keep this capitalize/2
implementation by elixir is because majority of developer's would expect it to work this way.
This answer made me generally curious around reasoning that could have gone around it. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With