Sha256: 6c4fcc1eb419e0c9afa4a79b51ce571544b9a495fee13055807aaa5da3a9af18

Contents?: true

Size: 1.09 KB

Versions: 73

Compression:

Stored size: 1.09 KB

Contents

defmodule PigLatin do
  @doc """
  Given a `phrase`, translate it a word at a time to Pig Latin.

  Words beginning with consonants should have the consonant moved to the end of
  the word, followed by "ay".

  Words beginning with vowels (aeiou) should have "ay" added to the end of the
  word.

  Some groups of letters are treated like consonants, including "ch", "qu",
  "squ", "th", "thr", and "sch".

  Some groups are treated like vowels, including "yt" and "xr".
  """
  @spec translate(phrase :: String.t()) :: String.t()
  def translate(phrase) do
    phrase
    |> String.split(" ")
    |> Enum.map(&translate_word/1)
    |> Enum.join(" ")
  end

  defp translate_word(word) do
    word
    |> consonant_prefix_and_rest
    |> case do
      ["", _] -> word <> "ay"
      [consonant_prefix, rest] -> rest <> consonant_prefix <> "ay"
      _ -> word
    end
  end

  defp consonant_prefix_and_rest(word) do
    if Regex.match?(~r/^[yx][bcdfghjklmnpqrstvwxy]+/, word) do
      ["", word]
    else
      ~r/^(s?qu|(?:[^aeiou]*))?([aeiou].*)$/
      |> Regex.run(word, capture: :all_but_first)
    end
  end
end

Version data entries

73 entries across 73 versions & 1 rubygems

Version Path
trackler-2.2.1.180 tracks/elixir/exercises/pig-latin/example.exs
trackler-2.2.1.179 tracks/elixir/exercises/pig-latin/example.exs
trackler-2.2.1.178 tracks/elixir/exercises/pig-latin/example.exs
trackler-2.2.1.177 tracks/elixir/exercises/pig-latin/example.exs
trackler-2.2.1.176 tracks/elixir/exercises/pig-latin/example.exs
trackler-2.2.1.175 tracks/elixir/exercises/pig-latin/example.exs
trackler-2.2.1.174 tracks/elixir/exercises/pig-latin/example.exs
trackler-2.2.1.173 tracks/elixir/exercises/pig-latin/example.exs
trackler-2.2.1.172 tracks/elixir/exercises/pig-latin/example.exs
trackler-2.2.1.171 tracks/elixir/exercises/pig-latin/example.exs
trackler-2.2.1.170 tracks/elixir/exercises/pig-latin/example.exs
trackler-2.2.1.169 tracks/elixir/exercises/pig-latin/example.exs
trackler-2.2.1.167 tracks/elixir/exercises/pig-latin/example.exs
trackler-2.2.1.166 tracks/elixir/exercises/pig-latin/example.exs
trackler-2.2.1.165 tracks/elixir/exercises/pig-latin/example.exs
trackler-2.2.1.164 tracks/elixir/exercises/pig-latin/example.exs
trackler-2.2.1.163 tracks/elixir/exercises/pig-latin/example.exs
trackler-2.2.1.162 tracks/elixir/exercises/pig-latin/example.exs
trackler-2.2.1.161 tracks/elixir/exercises/pig-latin/example.exs
trackler-2.2.1.160 tracks/elixir/exercises/pig-latin/example.exs