UNPKG

@alu0100953275/constant-folding

Version:
80 lines (64 loc) 2.14 kB
// See https://github.com/babel/minify/tree/master/packages/babel-plugin-minify-constant-folding const fs = require("fs"); const deb = require('../src/deb.js'); const escodegen = require("escodegen"); const espree = require("espree"); const estraverse = require("estraverse"); "use strict"; module.exports = constantFolding; /** * * @param {string} code A string of code to be fold * * @description A function that with a code given do a constant folding and return it folded. * Fist it parse de code given to a ast node, then we can work with it * using estraverse and then calling the fuction replaceByLiteral the code gets * folded in ast mode, then we regenerate the code with the new ast generated * * @returns {string} Returns the code with constant folding */ function constantFolding(code/* , pattern */) { const t = espree.parse(code , { ecmaVersion: 6, loc: false }); estraverse.traverse(t, { leave: function (n) { if ( n.type == "BinaryExpression" && n.left.type == "Literal" && n.right.type == "Literal") { replaceByLiteral(n); } // if (n.type == "CallExpression" && // n.callee.property.name == "join") { replaceByLiteralOfJoin(n); } }, }); // deb(t); let c = escodegen.generate(t); return c } /** * A function that replace the node of a binary expression given by a literal of * the result itself * @param {node} n node of binary expression (ast) */ function replaceByLiteral(n) { n.type = "Literal"; n.value = eval(`${n.left.raw}${n.operator}${n.right.raw}`); n.raw = String(n.value); delete n.left; delete n.right; } /** * A function that replace a join saving the result in a literal * * @param {node} n */ // function replaceByLiteralOfJoin(n) { // let param = n.arguments[0].raw; // let string = []; // for (elements of n.callee.object.elements) { // string.push(elements.raw); // } // n.type = "Literal"; // n.value = eval(`[${string}].${n.callee.property.name}(${param})`); // n.raw = String(n.value); // delete n.range; // delete n.callee; // delete n.arguments; // }