Pregunta

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)
¿Fue útil?

Solución

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).

Otros consejos

I don't believe it's possible to interact with generated variables like _results directly from CoffeeScript. You could, however, do so with escaped JavaScript (which the compiler simply ignores):

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

compiles to

Array.prototype.unique = function() {
  var value, _i, _len, _results;
  _results = [];
  for (_i = 0, _len = this.length; _i < _len; _i++) {
    value = this[_i];
    if (!value in _results) {
      _results.push(value);
    }
  }
  return _results;
};

Stylistically, though, I think it'd be preferable to code your list comprehension in pure CoffeeScript. It's just 3 lines:

Array::unique = ->
  results = []
  results.push value for value in this when value not in results
  results

As to your implementation of the unique function (and I realize this is a bit of an aside), you should be aware that it's not going to scale well for large N, since it has to iterate through increasingly large arrays (except in special cases where the runtime's indexOf has better than O(N) efficiency). It's possible to handle large N relatively efficiently using a hash, though; see my proposed implementation of Underscore.js' _.uniq here.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top