I am beginner of CoffeeScript and Jasmine. At first, I tried to pass test with below code:
class Counter
count: 0
constructor: ->
@count = 0
increment: ->
@count++
decrement: ->
@count--
reset: ->
@count = 0
root = exports ? this
root.Counter = Counter
The jasmine test code is below:
describe("Counter", ->
counter = new Counter
it("shold have 0 as a count variable at first", ->
expect(counter.count).toBe(0)
)
describe('increment()', ->
it("should count up from 0 to 1", ->
expect(counter.increment()).toBe(1)
)
)
)
Then kind person told me that the code should be as below:
class Counter
count: 0
constructor: ->
@count = 0
increment: ->
++@count
decrement: ->
--@count
reset: ->
@count = 0
root = exports ? this
root.Counter = Counter
Yes, this code passed the test. But I have a question that the former code is more natural than latter code. I have no idea how to certain this question. Thank you for your help.
you could change your code to the following to be more clear about return values if you choose to stick to post increment
or you could change your test to:
but then you don’t expect the returned value of increment and decrement to reflect the updated value of @count
here’s an example to play with that will make the differences obvious:
http://coffeescript.org/#try:class%20Counter%20%20count%3A%200%20%20increment%3A%20-%3E%20%20%20%20%40count%2B%2B%20%20%20%20%40count%20%20%20%20inc%3A%20-%3E%20%20%20%20%40count%2B%2B%20%20decrement%3A%20-%3E%20%20%20%20–%40count%20%20dec%3A%20-%3E%20%20%20%20%40count–cnt%20%3D%20new%20Counteralert%20cnt.increment()alert%20cnt.countalert%20cnt.inc()alert%20cnt.countalert%20cnt.decrement()alert%20cnt.countalert%20cnt.dec()alert%20cnt.count