Skip to content

Commit

Permalink
Fix guarded expressions being utilized elsewhere (#179)
Browse files Browse the repository at this point in the history
+ (Close #171)
+ (close #174)
+ (close #176)
  • Loading branch information
boopathi authored and kangax committed Oct 5, 2016
1 parent 23aec22 commit 11664eb
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ describe("guarded-expressions-plugin", () => {
alert(new Foo() || false);
`);
expected = unpad(`
alert(new Foo());
alert(new Foo() || false);
`);
expect(transform(source)).toBe(expected);
});
Expand Down
14 changes: 12 additions & 2 deletions packages/babel-plugin-minify-guarded-expressions/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,24 @@ module.exports = function({ types: t }) {

const left = path.get("left");
const right = path.get("right");

// issues - 171, 174, 176
// we assume that it is returned/assigned/part of a bigger expression
// or utilized somehow
// we check if we shouldBail only when evaluating
// the rightside of the expression;
// if the left side is evaluated to be deterministic,
// we can safely replace the entire expression
const shouldBail = !path.parentPath.isExpressionStatement();

if (node.operator === "&&") {
const leftTruthy = left.evaluateTruthy();
if (leftTruthy === false) {
// Short-circuit
path.replaceWith(node.left);
} else if (leftTruthy === true && left.isPure()) {
path.replaceWith(node.right);
} else if (right.evaluateTruthy() === false && right.isPure()) {
} else if (right.evaluateTruthy() === false && right.isPure() && !shouldBail) {
path.replaceWith(node.left);
}
} else if (node.operator === "||") {
Expand All @@ -34,7 +44,7 @@ module.exports = function({ types: t }) {
} else if (leftTruthy === true) {
// Short-circuit
path.replaceWith(node.left);
} else if (right.evaluateTruthy() === false && right.isPure()) {
} else if (right.evaluateTruthy() === false && right.isPure() && !shouldBail) {
path.replaceWith(node.left);
}
}
Expand Down

0 comments on commit 11664eb

Please # to comment.