Bloated JS from Coffeescript which wants to return

2019-03-03 20:14发布

问题:

I've got this Coffeescript here:

brew = (args...) =>
  for e in args
    alert e
    null

brew('fo', 're', 'eo');

I wish I didn't need to put null there to get it to work, but alas, that compiles to this:

brew = function() {
  var args, e, _i, _len, _results;
  args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
  _results = [];
  for (_i = 0, _len = args.length; _i < _len; _i++) {
    e = args[_i];
    alert(e);
    _results.push(null);
  }
  return _results;
};

brew('fo', 're', 'eo');

But now I have 3 unnecessary lines:

 _results = [];
 _results.push(null);
 return _results;

Any tips?

回答1:

What about this

brew = (args...) -> args.forEach alert

which compiles to

var brew,
    __slice = [].slice;

brew = function() {
  var args;
  args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
  return args.forEach(alert);
};

brew('fo', 're', 'eo');


回答2:

If you don't want a function to return anything, say so:

brew = (args...) =>
  for e in args
    console.log e
  return

A side effect of that is that the for loop won't populate an array: CoffeeScript can guarantee that the result of the for loop expression won't be used so it won't bother calculating it. Keep in mind that everything is an expression in CoffeeScript and functions return the value of their last expression so sometimes you have to throw in explicit returns to avoid wasting time computing things that will never get used.

That CoffeeScript loop ends up like this:

for (_i = 0, _len = args.length; _i < _len; _i++) {
  e = args[_i];
  console.log(e);
}

Note that the explicit "return nothing" return suppresses all the _result stuff.

You can see it yourself over here.