One of the most succinct (and quite performant) solutions would be based on regular expressions (also called regexes). Julia does have a regex support (see the docs). Although at first glance such regexes seem arcane and off-putting, we’ll explore this venue in Section 18.1. For now, in order to keep things simple our approach will rely on good old for loops and conditionals.
First changeToSnakeCase as it is simpler to write (start small and build).
function changeToSnakeCase(camelCasedWord::Str)::Str
result::Str = ""
for c in camelCasedWord
result *= isuppercase(c) ? '_' * lowercase(c) : c
end
return result
end
We begin with an empty result. Next, we travel through each character (c) of our camelCasedWord if a letter is uppercased (isuppercase(c) ?) we update our result (*=) by appending to it underscore ('_') concatenated (*) with the lowercased character (lowercase(c)). Otherwise (:) we append the character unchanged (c). Finally, we return the result.
Let’s see if it works.
map(changeToSnakeCase, ["helloWorld",
"niceToMeetYou", "translateToEnglish"])
["hello_world", "nice_to_meet_you", "translate_to_english"]
Looks good. Time for the other function.
function changeToCamelCase(snakeCasedWord::Str)::Str
result::Str = ""
prevUnderscore::Bool = false
for c in snakeCasedWord
if c == '_'
prevUnderscore = true
continue
else
result *= prevUnderscore ? uppercase(c) : c
prevUnderscore = false
end
end
return result
end
One more time, we begin with an empty result (result::Str = ""), but this time we also declare an indicator that tells us whether the previously examined letter was an underscore (prevUnderscore). Next, we traverse the snakeCasedWord character by character (for c in snakeCasedWord) and build up the result. If the currently examined character is an underscore (if c == '_') we set the indicator to true and skip rest of the code in the for loop (in this iteration only) with continue. Otherwise (else), we append the character to the result (result *=) with the proper casing based on the value of prevUnderscore and set this last variable to false. Once we’re done, we return the result.
Time for another test.
map(changeToCamelCase,
["hello_world", "nice_to_meet_you", "translate_to_english"])
["helloWorld", "niceToMeetYou", "translateToEnglish"]
And another small success.