Skip to content

Instantly share code, notes, and snippets.

@FrancoB411
Last active June 8, 2018 15:49
Show Gist options
  • Save FrancoB411/8f49350ded630b5f5d84f425968df836 to your computer and use it in GitHub Desktop.
Save FrancoB411/8f49350ded630b5f5d84f425968df836 to your computer and use it in GitHub Desktop.
Some refactors to reduce the API surface area, make operations dryer and more maintainable, better naming
class Calculator
ORDERED_OPERATIONS = %W(* / + -)
def calculate(input)
input = input.split(" ")
while input.length > 1 do
ORDERED_OPERATIONS.each do | op |
i = input.find_index(op)
if i
prev = input[i-1].to_f
nex = input[i+1].to_f
result = operate(prev, op, nex)
input = update_input_with_result(input, result, i)
end
end
end
input.first
end
private
def operate(prev, op, nex)
prev.send(op, nex)
end
def update_input_with_result(input, result, i)
input.slice!((i-1)..(i+1)) #extract evaluated items
input[i-1] = result #insert result
input
end
end
input = '7 - 2 + 3 / 4 * 5'
expected = (7 - (2 + (3 / (4 * 5.to_f))))
actual = Calculator.new.calculate(input)
puts actual
puts (expected == actual)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment