From ac09610e8147e840f32fda94ed8a6033dc2ec437 Mon Sep 17 00:00:00 2001 From: echo094 <20028238+echo094@users.noreply.github.com> Date: Sun, 22 Sep 2024 17:55:51 +0800 Subject: [PATCH] visitor(calculate-constant-exp): support more unary conditions. Signed-off-by: echo094 <20028238+echo094@users.noreply.github.com> --- src/visitor/calculate-constant-exp.js | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/visitor/calculate-constant-exp.js b/src/visitor/calculate-constant-exp.js index 80bd5d7..657df4f 100644 --- a/src/visitor/calculate-constant-exp.js +++ b/src/visitor/calculate-constant-exp.js @@ -50,6 +50,8 @@ function calculateBinaryExpression(path) { * - the operator is `!` and the argument is ArrayExpression or Literal. * - the operator is `-` and the argument is a negative number * - the operator is `+`, or `~`, and the argument is a number + * - the operator is 'void' and the argument is Literal. + * - the operator is 'typeof' and the argument is Literal. * * Otherwise, the expression can't be simplified. * For example, `typeof window` can be calculated but it's not constant. @@ -84,6 +86,19 @@ function calculateUnaryExpression(path) { } return } + if (node0.operator === 'void') { + if (isLiteral) { + path.replaceWith(t.identifier('undefined')) + } + return + } + if (node0.operator === 'typeof') { + if (isLiteral) { + const code = generator(node0).code + path.replaceWith(t.stringLiteral(eval(code))) + } + return + } } module.exports = {