Skip to content

Instantly share code, notes, and snippets.

@nathan-cruz77
Created August 26, 2018 18:25
Show Gist options
  • Save nathan-cruz77/0f22503e5d97ae87a90c0868303f9647 to your computer and use it in GitHub Desktop.
Save nathan-cruz77/0f22503e5d97ae87a90c0868303f9647 to your computer and use it in GitHub Desktop.
Extract operation from string and executes it
# Sample usage:
#
# iex(1)> Calculator.calculate('123 + 27')
# 150
# iex(2)> Calculator.calculate('123 - 27')
# 96
# iex(3)> Calculator.calculate('123 * 27')
# 3321
# iex(4)> Calculator.calculate('123 / 27')
# 4.555555555555555
#
defmodule Calculator do
def calculate(s) when is_list(s) do
s |> List.to_string() |> calculate()
end
def calculate(s) do
[a, operator, b] = Regex.run(~r/(\d+)\s*(\+|-|\*|\/)\s*(\d+)/, s, capture: :all_but_first)
a = String.to_integer(a)
b = String.to_integer(b)
operator = String.to_atom(operator)
apply(Kernel, operator, [a, b])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment