Skip to content

Commit

Permalink
optimizer: mark some new Date expressions pure
Browse files Browse the repository at this point in the history
  • Loading branch information
evanw committed Jan 18, 2023
1 parent acc5bec commit 31fb452
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
25 changes: 25 additions & 0 deletions internal/js_parser/js_parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -14381,6 +14381,31 @@ func (p *parser) maybeMarkKnownGlobalConstructorAsPure(e *js_ast.ENew) {
}
}

case "Date":
n := len(e.Args)

if n == 0 {
// "new Date()" is pure
e.CanBeUnwrappedIfUnused = true
break
}

if n == 1 {
switch js_ast.KnownPrimitiveType(e.Args[0]) {
case js_ast.PrimitiveNull, js_ast.PrimitiveUndefined, js_ast.PrimitiveBoolean, js_ast.PrimitiveNumber, js_ast.PrimitiveString:
// "new Date('')" is pure
// "new Date(0)" is pure
// "new Date(null)" is pure
// "new Date(true)" is pure
// "new Date(false)" is pure
// "new Date(undefined)" is pure
e.CanBeUnwrappedIfUnused = true

default:
// "new Date(x)" is impure because converting "x" to a string could have side effects
}
}

case "Set":
n := len(e.Args)

Expand Down
16 changes: 16 additions & 0 deletions internal/js_parser/js_parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5756,3 +5756,19 @@ func TestAutoPureForWeakMap(t *testing.T) {
expectPrinted(t, "new WeakMap([x, []])", "new WeakMap([x, []]);\n")
expectPrinted(t, "new WeakMap([[], x])", "new WeakMap([[], x]);\n")
}

func TestAutoPureForDate(t *testing.T) {
expectPrinted(t, "new Date", "/* @__PURE__ */ new Date();\n")
expectPrinted(t, "new Date(0)", "/* @__PURE__ */ new Date(0);\n")
expectPrinted(t, "new Date('')", "/* @__PURE__ */ new Date(\"\");\n")
expectPrinted(t, "new Date(null)", "/* @__PURE__ */ new Date(null);\n")
expectPrinted(t, "new Date(true)", "/* @__PURE__ */ new Date(true);\n")
expectPrinted(t, "new Date(false)", "/* @__PURE__ */ new Date(false);\n")
expectPrinted(t, "new Date(undefined)", "/* @__PURE__ */ new Date(void 0);\n")
expectPrinted(t, "new Date(`${foo}`)", "/* @__PURE__ */ new Date(`${foo}`);\n")
expectPrinted(t, "new Date(foo ? 'x' : 'y')", "/* @__PURE__ */ new Date(foo ? \"x\" : \"y\");\n")

expectPrinted(t, "new Date(foo)", "new Date(foo);\n")
expectPrinted(t, "new Date(foo``)", "new Date(foo``);\n")
expectPrinted(t, "new Date(foo ? x : y)", "new Date(foo ? x : y);\n")
}

0 comments on commit 31fb452

Please sign in to comment.