@alu0101337760/constant-folding
Version:
Constant Folding javascript code
98 lines (79 loc) • 2.46 kB
JavaScript
// 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");
;
module.exports = constantFolding;
/**
* A function that takes a js code as argument and returns the same version
* after applying constant folding.
*
* @param {string} code A string with the input code.
*
* @returns {string} Returns the equivalent code after applying constant folding.
*/
function constantFolding(code) {
const t = espree.parse(code, { ecmaVersion: 6, loc: false });
estraverse.traverse(t, {
leave: function (n) {
replaceExpression(n);
},
});
return escodegen.generate(t);
}
/**
* @description This function replaces the input node by its equivalent after applying constant folding
* @param {Node} n
*/
function replaceExpression(n) {
if (n.type == "BinaryExpression" &&
n.left.type == "Literal" && n.right.type == "Literal") {
replaceByLiteral(n);
}
if (n.type == "MemberExpression" && n.object.type == "ArrayExpression") {
if (n.property.type == "Identifier" && n.property.name == "length") {
replaceLength(n);
}
else if (n.property.type == "Literal") {
replaceLiteralAsIndex(n);
}
}
}
/**
* @description This function replaces expressions of the type [1,2,3][2-1]
* @param {Node} node
*/
function replaceLiteralAsIndex(node) {
node.type = "Literal";
let index = node.property.value;
node.value = eval(`${node.object.elements[index].value}`);
node.raw = String(node.value);
delete node.object;
delete node.property;
delete node.computed;
}
/**
* @description This function replaces expressions of the type [1,2,3].length
* @param {Node} node
*/
function replaceLength(node) {
node.type = "Literal";
node.value = eval(`${node.object.elements.length}`);
node.raw = String(node.value);
delete node.object;
delete node.property;
delete node.computed;
}
/**
* @description This function replaces this node contents with the reusult of running its operation with its left and right.
* @param {Node} node
*/
function replaceByLiteral(node) {
node.type = "Literal";
node.value = eval(`${node.left.raw} ${node.operator} ${node.right.raw}`);
node.raw = String(node.value);
delete node.left;
delete node.right;
}