Skip to content

Instantly share code, notes, and snippets.

@adomokos
Created October 2, 2011 12:37
Show Gist options
  • Save adomokos/1257409 to your computer and use it in GitHub Desktop.
Save adomokos/1257409 to your computer and use it in GitHub Desktop.
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