facebookarchive/prepack

Verbose scope output for an IIFE

Open

#1,892 opened on May 8, 2018

View on GitHub
 (2 comments) (0 reactions) (0 assignees)JavaScript (520 forks)batch import
enhancementhelp wantedserializer

Repository metrics

Stars
 (14,268 stars)
PR merge metrics
 (No merged PRs in 30d)

Description

I noticed that just wrapping code into an IIFE changes makes the scope output verbose.

Before:

const x = 5;
const getDoubleOfX = () => 2 * x;
const setX = (newX) => { x = newX; }

global.getDoubleOfX = getDoubleOfX;
global.setX = setX;

Output:

let x;

(function () {
  var _0 = function () {
    return 2 * x;
  };

  var _1 = function (newX) {
    x = newX;
  };

  getDoubleOfX = _0;
  setX = _1;
  x = 5;
})();

After:

(function() {
  const x = 5;
  const getDoubleOfX = () => 2 * x;
  const setX = (newX) => { x = newX; }
  
  global.getDoubleOfX = getDoubleOfX;
  global.setX = setX;
})();

Output:

(function () {
  var __scope_0 = Array(1);

  var __scope_1 = function (__selector) {
    var __captured;

    switch (__selector) {
      case 0:
        __captured = [5];
        break;

      default:
        throw new Error("Unknown scope selector");
    }

    __scope_0[__selector] = __captured;
    return __captured;
  };

  var _0 = function () {
    var __captured__scope_2 = __scope_0[0] || __scope_1(0);

    return 2 * __captured__scope_2[0];
  };

  var _2 = function (newX) {
    var __captured__scope_2 = __scope_0[0] || __scope_1(0);

    __captured__scope_2[0] = newX;
  };

  getDoubleOfX = _0;
  setX = _2;
})();

I understand scope tracking makes sense when the closure is reused. But if it's just an IIFE, can we optimize and produce cleaner output?

Contributor guide