4.2 Solution

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) and we will explore this venue in Section 27.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 an examined 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
        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 call it a day until the current spin of the for loop ends. Otherwise (else), we append the character to the result (result *=) with the proper casing determined based on the value of prevUnderscore and set this last variable to false.

Time for another test.

map(changeToCamelCase,
    ["hello_world", "nice_to_meet_you", "translate_to_english"])
["helloWorld", "niceToMeetYou", "translateToEnglish"]

And another small victory.



CC BY-NC-SA 4.0 Bartlomiej Lukaszuk