Sha256: a5c06e01afa6d2f7437c7964cdf398ad5a01a4cbb87a99dacf9c4e560748ec0d

Contents?: true

Size: 1.07 KB

Versions: 81

Compression:

Stored size: 1.07 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/^yt|xr/, word) do
      ["", word]
    else
      ~r/^(s?qu|(?:[^aeiou]*))?([aeiou].*)$/
      |> Regex.run(word, capture: :all_but_first)
    end
  end
end

Version data entries

81 entries across 81 versions & 1 rubygems

Version Path
trackler-2.2.1.105 tracks/elixir/exercises/pig-latin/example.exs
trackler-2.2.1.104 tracks/elixir/exercises/pig-latin/example.exs
trackler-2.2.1.103 tracks/elixir/exercises/pig-latin/example.exs
trackler-2.2.1.102 tracks/elixir/exercises/pig-latin/example.exs
trackler-2.2.1.101 tracks/elixir/exercises/pig-latin/example.exs
trackler-2.2.1.100 tracks/elixir/exercises/pig-latin/example.exs
trackler-2.2.1.99 tracks/elixir/exercises/pig-latin/example.exs
trackler-2.2.1.98 tracks/elixir/exercises/pig-latin/example.exs
trackler-2.2.1.97 tracks/elixir/exercises/pig-latin/example.exs
trackler-2.2.1.96 tracks/elixir/exercises/pig-latin/example.exs
trackler-2.2.1.95 tracks/elixir/exercises/pig-latin/example.exs
trackler-2.2.1.94 tracks/elixir/exercises/pig-latin/example.exs
trackler-2.2.1.93 tracks/elixir/exercises/pig-latin/example.exs
trackler-2.2.1.92 tracks/elixir/exercises/pig-latin/example.exs
trackler-2.2.1.91 tracks/elixir/exercises/pig-latin/example.exs
trackler-2.2.1.90 tracks/elixir/exercises/pig-latin/example.exs
trackler-2.2.1.89 tracks/elixir/exercises/pig-latin/example.exs
trackler-2.2.1.88 tracks/elixir/exercises/pig-latin/example.exs
trackler-2.2.1.87 tracks/elixir/exercises/pig-latin/example.exs
trackler-2.2.1.86 tracks/elixir/exercises/pig-latin/example.exs