DEV Community

Discussion on: Daily Challenge #29 - Xs and Os

Collapse
 
thepeoplesbourgeois profile image
Josh • Edited
const exsAndOhs = // "πŸŽ™ they haunt me…" (https://www.youtube.com/watch?v=0uLI6BnVh6w)
  (string) => string
    .toLowerCase()
    .split("")
    .reduce((count, letter) =>
      /x/.test(letter) ? count += 1
        : /o/.test(letter) ? count -= 1
        : count
    , 0) === 0;


exsAndOhs("xoxo") // => true
exsAndOhs("like ghosts, they want me") // => false
exsAndOhs("to make them all, they won't let go") // => false
exsAndOhs("ex's and ohs") // => true

TERNARY CHAINS?? Yeah. I'm a loner, Dottie. A rebel…

Collapse
 
thepeoplesbourgeois profile image
Josh • Edited

Now in elixir because hey all the cool kids are using not-Javascript here.

defmodule ExsAndOhs do

  def try_to_get_over_them(string) do
    string
      |> String.downcase
      |> test(0) # The `Enum` module's for chumps.
  end

  defp test("", count), do: count == 0  # whole string is traversed
  defp test("x" <> string, count), do:  # next grapheme is an "x"
    test(string, count + 1)             
  defp test("o" <> string, count), do:  # next grapheme is an "o"
    test(string, count - 1) 
  defp test(string, count), do:         # String.next_grapheme/1 is a tuple πŸ˜ƒ
    string
      |> String.next_grapheme
      |> elem(1)
      |> test(count)

end