Source: utils.js

const espree = require("espree");

/**
 * Creates a new AST node containing the info received
 * @param {string} literal to be assigned as value of the node
 * @returns {Object} the resulting AST node
 */
const newNode = (literal) => {
  return espree.parse(literal, { ecmaVersion: 6 }).body[0].expression
}

/**
 * Translates a js Array into an AST node containing its information
 * @param {Array} array to be translated
 * @returns {Object} the resulting AST node
 */
const newArrayNode = (array) => {
  return {
    "type": "ArrayExpression",
    "elements": array.map((element) => newNode(element))
  }
}

/**
 * Checks if an AST node's info is of constant nature
 * @param {Object} code to be checked
 * @returns {bool} 
 */
const isConstant = (code) => {
  return code.type === "Literal" ||
    code.type === "Identifier" ||
    Array.isArray(code) && code.every((val) => isConstant(val)) ||
    code.type === "ArrayExpression" && code.elements.every((val) => isConstant(val)) ||
    code.type == "BinaryExpression" && code.left.type == "Literal" && code.right.type == "Literal";
}

/**
 * Extracts the "value" of an AST node, it being its id, raw value, or array of elements
 * @param {Object} node 
 * @returns {*} the value contained in the node
 */
const getValue = (node) => {
  return node.raw ? `${node.raw}` :
    node.id ? node.id :
      node.name ? node.name :
        node.elements ? node.elements.map(e => getValue(e)) : "";
}


module.exports = {
  newNode,
  getValue,
  newArrayNode,
  isConstant
}