Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 | 1x 1x 1x 1x 1x 1x 1x 8x 8x 63x 8x 63x 9x 63x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x | // 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;
/**
* 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 Eif (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;
}
|