minify icon indicating copy to clipboard operation
minify copied to clipboard

Eliminate if statements when condition is provably true/false

Open iccir opened this issue 7 years ago • 2 comments

Assume the following code:

function foo() {
    if (bar() || true) {
        baz();
    } else {
        NOT_REACHABLE();
    }
}

Currently, babel-minify transforms this to:

function foo(){bar()||!0?baz():NOT_REACHABLE()}foo();

UglifyJS3 transforms to:

function foo(){bar(),baz()}foo();

It would be nice if babel-minify could eliminate the if statement entirely.

iccir avatar Nov 15 '18 03:11 iccir

The issue is that it can't evaluate bar() || true, since it could be either true or 42 depending on whether bar() returns false or 42, and can't currently evaluate stuff to don't-know-exactly-what-but-something-truthy.

If using , instead of ||, it eliminates not just the if, but the bar(), too:

'use strict';
function foo() {
    if (bar(), true) {
        baz();
    } else {
        NOT_REACHABLE();
    }
}
//With just deadcode: (correct)
"use strict";function foo(){bar();baz()}
//With just simplify: (correct)
"use strict";function foo(){(bar(),true)?baz():NOT_REACHABLE()}
//With simplify followed by deadcode: (wrong)
"use strict";function foo(){baz()}

Cyp avatar Nov 16 '18 09:11 Cyp

Oh yikes! Removing bar() in your example seems like a major bug (my original issue was more of a feature request).

iccir avatar Nov 16 '18 12:11 iccir