Skip to content

Commit

Permalink
enhance if_return (#5588)
Browse files Browse the repository at this point in the history
fixes #5587
  • Loading branch information
alexlamsl authored Jul 30, 2022
1 parent ab5c7e6 commit 6667440
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 3 deletions.
4 changes: 2 additions & 2 deletions lib/compress.js
Original file line number Diff line number Diff line change
Expand Up @@ -3567,7 +3567,7 @@ Compressor.prototype.compress = function(node) {
continue;
}
// if (foo()) return bar() ? x : void 0; ---> return foo() && bar() ? x : void 0;
// if (foo()) return bar() ? void 0 : x; ---> return foo() || bar() ? void 0 : x;
// if (foo()) return bar() ? void 0 : x; ---> return !foo() || bar() ? void 0 : x;
var or;
if (value instanceof AST_Conditional
&& ((or = is_undefined(value.consequent, compressor))
Expand All @@ -3577,7 +3577,7 @@ Compressor.prototype.compress = function(node) {
ret.value = value.clone();
ret.value.condition = make_node(AST_Binary, stat, {
operator: or ? "||" : "&&",
left: stat.condition,
left: or ? stat.condition.negate(compressor) : stat.condition,
right: value.condition,
});
statements.splice(i, 1, ret.transform(compressor));
Expand Down
46 changes: 45 additions & 1 deletion test/compress/if_return.js
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,7 @@ if_return_cond_void_2: {
}
expect: {
function f(a) {
return a || console.log("foo") ? void 0 : console.log("bar");
return !a || console.log("foo") ? void 0 : console.log("bar");
}
f();
f(42);
Expand Down Expand Up @@ -1827,3 +1827,47 @@ issue_5586: {
"baz",
]
}

issue_5587_1: {
options = {
if_return: true,
}
input: {
function f(a) {
if (console)
return a ? void 0 : console.log("PASS");
}
f();
f(42);
}
expect: {
function f(a) {
return !console || a ? void 0 : console.log("PASS");
}
f();
f(42);
}
expect_stdout: "PASS"
}

issue_5587_2: {
options = {
if_return: true,
}
input: {
function f(a) {
if (console)
return a ? console.log("PASS") : void 0;
}
f();
f(42);
}
expect: {
function f(a) {
return console && a ? console.log("PASS") : void 0;
}
f();
f(42);
}
expect_stdout: "PASS"
}

0 comments on commit 6667440

Please sign in to comment.