Search code examples
for-loopcoffeescriptaccumulator

Is it safe to reference the accumulator during a for loop?


Is there a correct way to reference the output of an for loop in CoffeeScript. It seems that using the internal variable _results works some of the time, but it does work in some situations (shown below). Is there a "correct" way to reference the accumulator that is stable?

Works

Array::unique = ->
  value for value in this when not (value in _results)

Doesn't work (renames iterator to _results2)

Array::unique = ->
  _results = null
  value for value in this when not (value in _results)

Also doesn't work (renames iterator to _results2)

Array::unique = ->
  value for value in (value for value in this) when not (value in _results)

Solution

  • The accumulator is an implementation detail. You're not meant to interact with it. That's why it renames the variable if you're already using the name. It sounds like you want the reduce() function (Firefox has it built in and most of the popular libraries include support for it).