Amberlamps
Amberlamps

Reputation: 40478

How to use variables in list comprehensions?

I have following Coffeescript code:

result = ([number, process = number * 2, process] for number in [1, 2, 3])

Which compiles into:

var number, process, result;

result = (function() {
  var _i, _len, _ref, _results;
  _ref = [1, 2, 3];
  _results = [];
  for (_i = 0, _len = _ref.length; _i < _len; _i++) {
    number = _ref[_i];
    _results.push([number, process = number * 2, process]);
  }
  return _results;
})();

The result is a multidimensional array:

[ [1, 2, 2], [2, 4, 4], [3, 6, 6] ]

Let´s assume that process is calculated very costly and I want to use that value as argument for several different functions:

result = ([number, process = /* costly calculation */, function1(process), function2(process), function3(process)] for number in [1, 2, 3])

This works actually fine. However, I do not want the value of process itself to be an element of the resulting array. Its value is now still the second element of the array. When I look at the compiled Javascript I can easily move the definition of process out of the array like that:

for (_i = 0, _len = _ref.length; _i < _len; _i++) {
    number = _ref[_i];
    process = number * 2;
    _results.push([number, process]);
}

How can I do that in Coffeescript?

Try it online!

Upvotes: 2

Views: 86

Answers (2)

epidemian
epidemian

Reputation: 19229

In CoffeeScript blocks are expressions too, so you can do:

result = (process = costlyCalculation(); [number, function1(process), function2(process), function3(process)] for number in [1, 2, 3])

Or, instead of using semicolons to separate statements, i'd recommend using newlines:

result = for number in [1, 2, 3]
  process = costlyCalculation()
  [number, function1(process), function2(process), function3(process)]

Upvotes: 1

RAM
RAM

Reputation: 2419

Do this one and this should solve your problem:

result = ([number = (process = /* costly calculation */) - process + number, function1(process), function2(process), function3(process)] for number in [1, 2, 3])

Here, two extra operations (addition and subtraction) will be done for every number in the array. But, it should not add too much to calculation costs.

It can be optimized further to bring down the calculation cost.

Update:

Use this one when you don't need variables number, process:

result = ([function1(process = /* costly calculation */), function2(process), function3(process)] for number in [1, 2, 3])

Upvotes: 1

Related Questions