Skip to content

Instantly share code, notes, and snippets.

@agonzalez0515
Created September 17, 2019 21:43
Show Gist options
  • Save agonzalez0515/8aa5f59fa102464a0781d4bb796142a6 to your computer and use it in GitHub Desktop.
Save agonzalez0515/8aa5f59fa102464a0781d4bb796142a6 to your computer and use it in GitHub Desktop.
String calculator using TDD | Team Cheese πŸ§€
class StringCalculator
def self.add(numbers_string)
invalid_input?(numbers_string) ? "Invalid Input" : add_all_numbers(numbers_string)
end
def self.invalid_input?(input_string)
input_string.include?('-') || input_string.include?('.')
end
def self.add_all_numbers(numbers)
numbers.split(/:|,/).reduce(0) {|sum,n| sum + n.to_i}
end
end
//tests
require 'string_calculator'
describe StringCalculator do
it "returns 0 for an empty string" do
expect(StringCalculator.add("")).to eq(0)
end
it "returns 1 for '1'" do
expect(StringCalculator.add("1")).to eq(1)
end
it "returns 2 for '1,1'" do
expect(StringCalculator.add("1,1")).to eq(2)
end
it "returns 10 for '10'" do
expect(StringCalculator.add("10")).to eq(10)
end
it "returns 106 for '1,100,5' " do
expect(StringCalculator.add("1,100,5")).to eq(106)
end
it "returns 5 for '2:3'" do
expect(StringCalculator.add("2:3")).to eq(5)
end
it "returns 76 for '45:22,9'" do
expect(StringCalculator.add("45:22,9")).to eq(76)
end
it "returns 'Invalid Input' for '-1'" do
expect(StringCalculator.add("-1")).to eq("Invalid Input")
end
it "returns 'Invalid Input' for '45:22,-9'" do
expect(StringCalculator.add("45:22,-9")).to eq("Invalid Input")
end
it "returns 'Invalid Input' for '12,5.5'" do
expect(StringCalculator.add("12,5.5")).to eq("Invalid Input")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment