word_count

This commit is contained in:
2024-08-21 22:40:34 -04:00
parent d00a9787f9
commit d9bc141e51
10 changed files with 385 additions and 0 deletions

View File

@@ -0,0 +1,17 @@
defmodule WordCount do
@doc """
Count the number of words in the sentence.
Words are compared case-insensitively.
"""
@spec count(String.t()) :: map
def count(sentence) do
sentence
|> String.split(~r/[\s,.:!?_]+/, trim: true)
|> Enum.reject(&String.match?(&1, ~r/[&@$%^]+/))
|> Enum.map(&String.trim(&1, "'"))
|> Enum.reduce(%{}, fn word, acc ->
Map.update(acc, String.downcase(word), 1, &(&1 + 1))
end)
end
end