Skip to content

Commit

Permalink
JS: compress a?b(c):b(d) to b(a?c:d)
Browse files Browse the repository at this point in the history
  • Loading branch information
tdewolff committed Jun 4, 2022
1 parent c1fb3fc commit ccc7b83
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
1 change: 1 addition & 0 deletions js/js_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -627,6 +627,7 @@ func TestJS(t *testing.T) {
{`!!(a===b||c===d)`, `a===b||c===d`},
{`!(a!==null)`, `a===null`},
{`a==void 0`, `a==null`},
{`a?b(c):b(d)`, `b(a?c:d)`},
//{`if(a!==null&&a!==undefined)a.b()`, `a?.b()`}, // returns undefined instead of false
{`(a===null||a===undefined)?undefined:a()`, `a?.()`},
{`(a===null||a===undefined)?undefined:a[0]`, `a?.[0]`},
Expand Down
10 changes: 9 additions & 1 deletion js/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -829,6 +829,14 @@ func (m *jsMinifier) optimizeCondExpr(expr *js.CondExpr, prec js.OpPrec) js.IExp
// no need to check whether left/right need to add groups, as the space saving is always more
return nullishExpr
} else {
callX, isCallX := expr.X.(*js.CallExpr)
callY, isCallY := expr.Y.(*js.CallExpr)
if isCallX && isCallY && len(callX.Args.List) == 1 && len(callY.Args.List) == 1 && !callX.Args.List[0].Rest && !callY.Args.List[0].Rest && isEqualExpr(callX.X, callY.X) {
expr.X = callX.Args.List[0].Value
expr.Y = callY.Args.List[0].Value
return &js.CallExpr{callX.X, js.Args{[]js.Arg{{expr, false}}}, false} // recompress the conditional expression inside
}

// shorten when true and false bodies are true and false
trueX, falseX := isTrue(expr.X), isFalse(expr.X)
trueY, falseY := isTrue(expr.Y), isFalse(expr.Y)
Expand Down Expand Up @@ -860,7 +868,7 @@ func (m *jsMinifier) optimizeCondExpr(expr *js.CondExpr, prec js.OpPrec) js.IExp
if comma, ok := group.X.(*js.CommaExpr); ok && js.OpCoalesce <= exprPrec(comma.List[len(comma.List)-1]) {
expr.Cond = comma.List[len(comma.List)-1]
comma.List[len(comma.List)-1] = expr
return comma
return comma // recompress the conditional expression inside
}
}
}
Expand Down

0 comments on commit ccc7b83

Please sign in to comment.