HiveBrain v1.2.0
Get Started
← Back to all entries
patternModerate

Can this coffeescripts method be simplified?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thissimplifiedcancoffeescriptsmethod

Problem

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.

Solution

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.

Code Snippets

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

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

Context

StackExchange Code Review Q#10677, answer score: 11

Revisions (0)

No revisions yet.