Skip to content

Commit

Permalink
Do not remove undefined if it's a local var
Browse files Browse the repository at this point in the history
  • Loading branch information
kangax committed Jan 26, 2017
1 parent ba72329 commit f83b06c
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -203,4 +203,13 @@ describe("transform-remove-undefined-plugin", () => {
`);
expect(transform(source)).toBe(expected);
});

it("should remove not remove local undefined", () => {
const source = unpad(`
function foo(undefined) {
a = b, undefined;
return undefined;
}`);
expect(transform(source)).toBe(source);
});
});
15 changes: 10 additions & 5 deletions packages/babel-plugin-transform-remove-undefined/src/index.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
"use strict";

function isPureAndUndefined(rval) {
if (rval.isIdentifier() &&
rval.node.name === "undefined") {
function isPureAndUndefined(rval, scope = { hasBinding: () => false }) {

if (rval.isIdentifier() && rval.node.name === "undefined") {
// deopt right away if undefined is a local binding
if (scope.hasBinding(rval.node.name, true /* no globals */)) {
return false;
}
return true;
}

if (!rval.isPure()) {
return false;
}
Expand Down Expand Up @@ -85,7 +90,7 @@ module.exports = function() {

for (let i = 0; i < expressions.length; i++) {
const expr = expressions[i];
if (!isPureAndUndefined(expr)) continue;
if (!isPureAndUndefined(expr, path.scope)) continue;

// last value
if (i === expressions.length - 1) {
Expand All @@ -100,7 +105,7 @@ module.exports = function() {

ReturnStatement(path) {
if (path.node.argument !== null) {
if (isPureAndUndefined(path.get("argument"))) {
if (isPureAndUndefined(path.get("argument"), path.scope)) {
path.node.argument = null;
}
}
Expand Down

0 comments on commit f83b06c

Please # to comment.