patternModerate
Can this coffeescripts method be simplified?
Viewed 0 times
thissimplifiedcancoffeescriptsmethod
Problem
I'm new to coffeescripts. Can the
I tried removing the last total but coffeescripts compiler goes nut :-/
Any help greatly appreciate.
getSum method be simplified more? ThanksMyObject =
checkCondition: (num) ->
return true if num is 5
getSum: (num) ->
total = 0
total += i for i in [1..num] when @checkCondition i
totalI tried removing the last total but coffeescripts compiler goes nut :-/
Any help greatly appreciate.
Solution
First,
Then, you can convert the explicit loop into a
Note
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 xNote
=> 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 xContext
StackExchange Code Review Q#10677, answer score: 11
Revisions (0)
No revisions yet.