diff --git a/deadsunrise/calc.rb b/deadsunrise/calc.rb new file mode 100644 index 0000000..94be4f7 --- /dev/null +++ b/deadsunrise/calc.rb @@ -0,0 +1,47 @@ +class Calc + + def add(operation) + return 0 if operation == '' + @clean_operands = clean(operation) + calculate(@clean_operands) + end + + private + + def clean(operation) + operands = replace_delimiters(operation) + check_for_negative_operands?(operands) + reject_big(operands) + return operands + end + + + def replace_delimiters(operation) + delimiters = parse_delimiter(operation) + operands = operation.gsub(/\/\/.*\n/ , '') + delimiters.flatten.each { |d| operands.gsub!(d.to_s,',') } + operands.split(',').map! {|s| s.to_i } + end + + def parse_delimiter(operation) + delimiters = ["\n"] + delimiters << operation.scan(/\[([^[]+)\]/) + delimiters << operation.scan(/\/\/(.)\n/) + end + + def check_for_negative_operands?(operands) + negatives = operands.reject {|i| i >= 0 } + raise("negatives not allowed #{negatives.join(',')}") unless negatives.empty? + end + + + def reject_big(operands) + operands.reject! {|i| i > 1000} + end + + + def calculate(operands) + operands.reduce(:+) + end + +end diff --git a/deadsunrise/calc_spec.rb b/deadsunrise/calc_spec.rb new file mode 100644 index 0000000..f92985b --- /dev/null +++ b/deadsunrise/calc_spec.rb @@ -0,0 +1,66 @@ +require 'calc' + +describe 'calc' do + + describe 'add' do + + before(:each) do + @calc = Calc.new + end + + it "should return 0 with an empty arg" do + @calc.add("").should == 0 + end + + it "should return 1 with 1" do + @calc.add('1').should == 1 + end + + it "should return 3 with 1,2" do + @calc.add("1,2").should == 3 + end + + it "should sum 2 or more numbers" do + @calc.add("1,2,3").should == 6 + end + + it "should allow new lines between numbers" do + @calc.add("1,2,3").should == 6 + @calc.add("1\n2,3").should == 6 + end + + it "should allow different delimiters" do + @calc.add("//;\n1").should == 1 + @calc.add("//:\n1:2").should == 3 + @calc.add("//;\n1;2;3").should == 6 + + end + + it "should rise an exception if numbers are negative" do + lambda {@calc.add("-2")}.should raise_error(RuntimeError, 'negatives not allowed -2') + lambda {@calc.add("1,-2,3")}.should raise_error(RuntimeError, 'negatives not allowed -2') + lambda {@calc.add("//;\n1;2;1,-2,-3")}.should raise_error(RuntimeError, 'negatives not allowed -2,-3') + end + + + it "should ignore numbers bigger than 1000" do + @calc.add("1,2000,2").should == 3 + end + + it "should allow delimiters longer than 1 char" do + @calc.add("//[***]\n1***2***3").should == 6 + end + + it "should allow multiple delimiters" do + @calc.add("//[*][%]\n1*2%3").should == 6 + end + + it "should allow multiple delimiters longer than 1char" do + @calc.add("//[,,,][;][;;]\n1,,,2;3").should == 6 + @calc.add("//;[***]\n1,***2,3").should == 6 + end + + + end + +end