3
\$\begingroup\$

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.

\$\endgroup\$
0
11
\$\begingroup\$

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.

\$\endgroup\$
1
  • 2
    \$\begingroup\$ 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. \$\endgroup\$ Apr 7 '12 at 16:06
1
\$\begingroup\$

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
\$\endgroup\$
2
  • \$\begingroup\$ That is one liner even I don't understand how reduce works \$\endgroup\$
    – Kuntau
    Apr 7 '12 at 8:05
  • \$\begingroup\$ nice implementation \$\endgroup\$
    – Thomas
    May 11 '12 at 7:21
0
\$\begingroup\$

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

\$\endgroup\$
1
  • \$\begingroup\$ 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? \$\endgroup\$
    – Kuntau
    Apr 6 '12 at 20:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.