Bloated JS from Coffeescript which wants to return everything

一笑奈何 提交于 2019-12-31 05:07:08

问题


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.



来源:https://stackoverflow.com/questions/18899040/bloated-js-from-coffeescript-which-wants-to-return-everything

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!