exercism/elixir/word-count/lib/word_count.ex

18 lines
457 B
Elixir
Raw Normal View History

2024-08-22 02:40:34 +00:00
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