Skip to content

Instantly share code, notes, and snippets.

@mowat27
Last active December 21, 2015 11:29
Show Gist options
  • Save mowat27/6299506 to your computer and use it in GitHub Desktop.
Save mowat27/6299506 to your computer and use it in GitHub Desktop.
First stab at the string calculator kata using red-refactor-green and dependency injection as my only refactoring
describe "calculator" do
let(:calculator) { CalculatorFactory.new.create }
it "adds numbers" do
calculator.calculate("1 + 2").should == 3
end
it "adds big numbers" do
calculator.calculate("11 + 22").should == 33
end
it "subtracts numbers" do
calculator.calculate("2 - 1").should == 1
end
it "multiplies numbers" do
calculator.calculate("2 * 3").should == 6
end
it "divides numbers" do
calculator.calculate("12 / 3").should == 4
end
it "evaluates an empty string as zero" do
calculator.calculate("").should == 0
end
it "evaluates nonsense to zero" do
calculator.calculate("+ 1 2 3").should == 0
end
end
class CalculatorFactory
def create
evaluators = {
"+" => ->(a,b) { a + b },
"-" => ->(a,b) { a - b },
"*" => ->(a,b) { a * b },
"/" => ->(a,b) { a / b }
}
evaluators.default = ->(_, _) { 0 }
Calculator.new(Parser.new(evaluators))
end
end
class Calculator
def initialize(parser)
@parser = parser
end
def calculate(expression)
@parser.evaluate(expression)
end
end
class Parser
def initialize(evaluators)
@evaluators = evaluators
end
def evaluate(expression)
op1, operation, op2 = expression.split
@evaluators[operation].call(op1.to_i, op2.to_i)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment