三元表达式转if

 

https://www.jianshu.com/p/a3857fa5c899

 

const fs = require('fs');
const { parse } = require("@babel/parser");
const traverse = require("@babel/traverse").default;
const types = require("@babel/types");
const generator = require("@babel/generator").default;

let jscode = `

void(1 - 1 ? aa = b + 4 : c + 5 ? cc = a + 1 : b + 2 ? ee = c + 3 : ff = 4)

`;

let ast = parse(jscode);


const visitor =
    {
        ConditionalExpression: {
            exit(path) {
                let {test, consequent, alternate} = path.node;
                let new_consequent = types.BlockStatement([types.ExpressionStatement(consequent)]);
                let new_alternate = types.BlockStatement([types.ExpressionStatement(alternate)]);
                let if_node = types.IfStatement(test, new_consequent, new_alternate);
                path.replaceWithMultiple(if_node);
                path.stop()
            },
        }

    }


const visitor1 =
    {
        UnaryExpression(path) {
            let operator = path.node.operator;
            if (operator === "void") {
                path.replaceWithMultiple(path.node.argument)
            }
        },
    }

traverse(ast, visitor1);
traverse(ast, visitor);
let { code } = generator(ast);
console.log(code);

 

posted @ 2022-01-07 21:24  AngDH  阅读(328)  评论(0编辑  收藏  举报