Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Hackibou (09/01/2011) CoffeeScript file - working on the String Calculator kata
class StringCalculator
calculate: (input) ->
@validateArgument(input)
result = 0
result += parseInt(splitValue) for splitValue in @splitValues(input)
result
validateArgument: (input) ->
unless (input.match /\n$|,$/) == null
throw { name: "InvalidArgument", message: "Function argument has invalid character" }
splitValues: (input) ->
return input.split(',') if input.indexOf(',') > 0
input.split '\n'
describe "StringCalculator", ->
beforeEach ->
@calculator = new StringCalculator
describe "with simple cases", ->
it "returns 1 when the argument is '1'", ->
(expect @calculator.calculate("1")).toEqual 1
it "returns 3 when the argument is '3'", ->
(expect @calculator.calculate("3")).toEqual 3
describe "with multiple arguments", ->
it "returns 3 when the argument is '1,2'", ->
(expect @calculator.calculate("1,2")).toEqual 3
it "returns 6 when the argument is '1,2,3'", ->
(expect @calculator.calculate("1,2,3")).toEqual 6
describe "with different delimiters", ->
it "returns 3 when the argument is '1\\n,2'", ->
(expect @calculator.calculate("1,\n2")).toEqual 3
it "returns 6 when the argument is '1\\n2\\n3'", ->
(expect @calculator.calculate("1\n2\n3")).toEqual 6
describe "validating the argument", ->
it "errors out when called with '1,\\n'", ->
(expect => @calculator.calculate("1,\n")).toThrow("Function argument has invalid character")
it "errors out when called with '1,'", ->
(expect => @calculator.calculate("1,")).toThrow("Function argument has invalid character")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment