DEV Community

Discussion on: Daily Challenge #266 - Who Likes It?

Collapse
 
savagepixie profile image
SavagePixie

Elixir

There's probably a much simpler way to solve it, but hey, I basically know how to do pattern matching and recursion, so there we go:

defmodule Like do
  def who_likes(list) do
    count = Enum.count(list)
    _who_likes(list, count - 2)
    |> _add_likes(count)
    |> IO.puts
  end

  defp _add_likes(x, n) when (n < 2), do: "#{x} likes this"
  defp _add_likes(x, _), do: "#{x} like this"

  defp _who_likes([], _), do: "no one"
  defp _who_likes([ a | [] ], _), do: a
  defp _who_likes([ a, b | [] ], _), do: "#{a} and #{b}"
  defp _who_likes([ a, b, c | [] ], _), do: "#{a}, #{b} and #{c}"
  defp _who_likes([ a, b | _tail], count), do: "#{a}, #{b} and #{count} others"
end