Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions deadsunrise/calc.rb
Original file line number Diff line number Diff line change
@@ -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
66 changes: 66 additions & 0 deletions deadsunrise/calc_spec.rb
Original file line number Diff line number Diff line change
@@ -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