# Can this coffeescripts method be simplified?

I'm new to coffeescripts. Can the getSum method be simplified more? Thanks

MyObject =
checkCondition: (num) ->
return true if num is 5

getSum: (num) ->
total = 0
total += i for i in [1..num] when @checkCondition i
total


I tried removing the last total but coffeescripts compiler goes nut :-/

Any help greatly appreciate.

First, return true if num is 5 is the same as just num is 5.
Then, you can convert the explicit loop into a reduce (you can read about it in Wikipedia or MDN):

MyObject =
checkCondition: (num) -> num is 5

getSum: (num) ->
[0..num].reduce (x,y) =>
if @checkCondition y then x + y else x


Note => instead of plain -> after (x,y). This is fat arrow, it prevents the capture of @ the inside function.

• Using reduce is definitely the most elegant approach, but note that it's not supported in older browsers. You can either add it to the Array prototype yourself, or use the excellent Underscore.js library. Apr 7 '12 at 16:06

As written getSum will only ever return 0 or 5, but I assume this checkCondition is merely an example, so here is my answer:

MyObject =
checkCondition: (num) -> num is 5

getSum: (num) ->
total = (i for i in [1..num] when @checkCondition i).reduce ((x, y) -> x + y), 0

• That is one liner even I don't understand how reduce works Apr 7 '12 at 8:05
• nice implementation May 11 '12 at 7:21

It's not clear what you're trying to achieve here.

The getSum method looks fine. The checkCondition is overcomplicated: it better be checkCondition: (num) -> num is 5

• actually the checkCondition code was a long one but it is not important here.. I just want to know if it is possible to further simplify getSum to one line?
– Kuntau
Apr 6 '12 at 20:04