Hello everyone! I am working through @pragdave course on building a hangman app and would like to ask for some refactoring advice. I am about halfway through the course and I am working on building an app where the computer plays the hangman game.
I have the following code to retrieve the most commonly used letter in a list of words. It works as expected, but it does not read/feel very elegant and I suspect it’s overcomplicated, probably because of my OOP background. Could anyone offer some advice on how to clean this up?
@spec get_most_common_letter(possible_words) :: {:letter, :occurrence}
def get_most_common_letter(possible_words) do
Enum.reduce(possible_words, %{}, fn word, acc ->
get_word_most_common_letters(word, acc)
end)
|> Map.to_list()
|> List.keysort(1, :desc)
|> Enum.at(0)
end
defp get_word_most_common_letters(word, counts) do
chars = String.codepoints(word)
Enum.reduce(chars, counts, fn char, acc ->
Map.update(acc, char, 1, &(&1 + 1))
end)
end