escodegen icon indicating copy to clipboard operation
escodegen copied to clipboard

proposal: Add option to wrap all immediately-invoked functions in parentheses

Open sanex3339 opened this issue 8 years ago • 2 comments

It would be nice if escodegen will have option which will work similar to this package: https://github.com/nolanlawson/optimize-js

Why? No additional dependencies is required, no need to iterate through AST-tree twice, no problems with source map and looks like this package is very slow in getting of updates.

sanex3339 avatar Oct 10 '16 15:10 sanex3339

ping

sanex3339 avatar Oct 13 '16 08:10 sanex3339

This tweak seems to work for me. It wraps IIFE's like

var x = function() { return stuff }();
becomes
var x = (function() { return stuff })();

and leaves alone declared function variables:

var x = function() { return stuff };
diff --git a/escodegen.js b/escodegen.js
index 42c05ae..db129a5 100644
--- a/escodegen.js
+++ b/escodegen.js
@@ -1887,7 +1887,10 @@
             if (!(flags & F_ALLOW_CALL)) {
                 return ['(', result, ')'];
             }
-            return parenthesize(result, Precedence.Call, precedence);
+            // check if this CallExpression is an IIFE.  If so, then always wrap in parens.
+            return (expr.callee.id === null && expr.callee.params.length === 0) ? 
+               parenthesize(result, 0, 1) :
+               parenthesize(result, Precedence.Call, precedence);
         },
 
         NewExpression: function (expr, precedence, flags) {

Obviously this needs a settable option. But I have some free time tomorrow, and can make a proper pull request.

bobpearson avatar Mar 30 '17 22:03 bobpearson