Skip to content

Instantly share code, notes, and snippets.

@real34
Forked from chadrien/score.rb
Last active December 30, 2015 04:59
Show Gist options
  • Save real34/7779697 to your computer and use it in GitHub Desktop.
Save real34/7779697 to your computer and use it in GitHub Desktop.
# encoding: UTF-8
defmodule Score do
@missed "-"
@spare "/"
@strike "X"
def total(rolls) when is_bitstring(rolls) do
rolls |> String.codepoints |> total
end
def total([@strike, bonus1, bonus2 | tail]), do: bonus_points([bonus1, bonus2], tail)
def total([_, @spare, bonus1 | tail]), do: bonus_points([bonus1], tail)
def total([score | tail]), do: (score |> to_points) + total(tail)
def total([]), do: 0
defp bonus_points(bonus, tail) do
10 + total(bonus) + total(bonus ++ tail)
end
defp to_points(@strike), do: 10
defp to_points(@missed), do: 0
defp to_points(n), do: binary_to_integer(n)
end
# encoding: UTF-8
Code.load_file("score.exs")
ExUnit.start
defmodule ScoreTest do
use ExUnit.Case
test "score can have rolls given" do
rolls = "--------------------"
refute nil? Score.total(rolls)
end
test "all zero rolls should return zero" do
rolls = "--------------------"
expected = 0
assert expected == Score.total(rolls)
end
test "one 5 score and nine zeros should return 5" do
rolls = "5-------------------"
assert 5 == Score.total(rolls)
end
test "one strike followed by a 5 and 8 zeros should return 20" do
rolls = "X5-----------------"
assert 20 == Score.total(rolls)
end
test "one spare followed by a 5 and 8 zeros should return 20" do
rolls = "9/5----------------"
assert 20 == Score.total(rolls)
end
test "one spare of 8 followed by a 5 and 8 zeros should return 20" do
rolls = "8/5----------------"
assert 20 == Score.total(rolls)
end
test "two strikes followed by 8 zeros should return 30" do
rolls = "XX-----------------"
assert 30 == Score.total(rolls)
end
test "two strikes followed by 3 and 7 zeros should return 39" do
rolls = "XX3----------------"
assert 39 == Score.total(rolls)
end
test "ending with spare and two strikes + 3 should return 39" do
rolls = "--------------/XX3-"
assert 59 == Score.total(rolls)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment