All files constant-folding.js

100% Statements 17/17
100% Branches 5/5
100% Functions 3/3
100% Lines 17/17

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  1x 1x 1x 1x 1x   1x   1x                 25x 25x 25x 25x 25x                     10x 10x   100x     25x     10x    
// 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;
 
/**
 *  This function replaces the operation by a literal
 *  
 *  @param {Node} n 
 *
 */
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 blah
 * @param {string} code A string blah
 * blah document
 * @returns {string} Returns an AST tree with the correct output
 * 
 */
function constantFolding(code) {
  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); }
    },
  });
  return escodegen.generate(t);
}