还原数组

 

 

const parser = require("@babel/parser");
const traverse = require("@babel/traverse").default;

// 将js代码转换成AST
// const { parse } = require("@babel/parser");
// 用来遍历AST中的节点
// const traverse = require("@babel/traverse").default;
// AST转换成js
const generator = require("@babel/generator").default;
// 用来判断节点类型和生成新的节点
const types = require("@babel/types");


const jscode = `

var a = [1,2,3,[1213,234],{"code":"666"},window];
b = a[1] + a[2] + a[3];
c = a[4];
d = a[5];

`;
let ast = parser.parse(jscode);



const replaceArrayElements =
{//数组还原
    VariableDeclarator(path) {
        let { node, scope } = path;
        let { id, init } = node;
        if (!types.isArrayExpression(init)) return;

        const binding = scope.getBinding(id.name);
        if (!binding || !binding.constant) {
            return;
        }

        for (let referPath of binding.referencePaths) {
            let { node, parent } = referPath;
            if (!types.isMemberExpression(parent, { object: node }) || !types.isNumericLiteral(parent.property)) {
                return;
            };
        }

        for (let referPath of binding.referencePaths) {
            let { parent, parentPath } = referPath;
            let index = parent.property.value;
            parentPath.replaceWith(init.elements[index]);
        }
        path.remove();
    },
}

traverse(ast, replaceArrayElements);


let { code } = generator(ast);

console.log(code);

 

上一篇:近期业务大量突增微服务性能优化总结-4.增加对于同步微服务的 HTTP 请求等待队列的监控


下一篇:prometheus-04 Prometheus使用案例