npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@alu0101244488/ast-types

v1.1.1

Published

Package for the translation of the spread operator to older ecma standards

Downloads

8

Readme

AST-Types

Installation

For installation it is only required to use the next command:

npm install @alu0101244488/ast-types

You can see the npm package on the following link:

https://www.npmjs.com/package/@alu0101244488/ast-types

Usage as executable:

To execute you can use the following command where [inputFile] is the file with the javasctipt code to compute and [outputFile] is the file to print the corresponding code with the transformations applied. Note is that the -o [outputFile] or --output [outputFile] is optional and the resulting code will be displayed on terminal in any case (a test file is given to try).

cf [inputFile] -o [outputFile]

Other options suported are -h or --help, and -V or --version which shows all the corresponding information or the version of the package correspondingly.

Example of the execution. You can see more details about the result of the execution in the Examples section.

Usage from code:

The source file containis a function spreadOperatorTranspile() which is exported. This function needs a string o code as a parameter. This string should contain a javascript code and depending if its a restElement or a spreadElement it acts accordingly.

Functions implemented to to apply the constant folding:

  • constaSpreadOperatorTranspile()
/**
 * @desc Function that translates the spread operator from
 * 			 the ecma6 standard to older standards by removing it
 * 			 and changing it with its correspondenting expression.
 * @param {string} code input code
 * @returns {string} resulting code
 */
function spreadOperatorTranspile (code) {
  ...
}
  • replaceRestElement
/**
 * @desc Auxiliary function to the sreadOperator function that 
 * 			 in the case of an restElement node, remplaces it with 
 * 			 its correspondenting code
 * @param {node o path} node AST node of the ast to be modified
 * @param {nodeo path} parent AST parent node needed to modify
 */
function replaceRestElement(node, parent) {
  ...
}
  • replaceSpreadElement
/**
 * @desc Auxiliary function to the sreadOperator function that 
 * 			 in the case of an spreadElement node, remplaces it with 
 * 			 its correspondenting code
 * @param {node o path} node AST node of the ast to be modified
 * @param {nodeo path} parent AST parent node needed to modify
 */
function replaceSpreadElement(node, parent) {
  ...
}

Deprecated verisions

Two versions were tried before. Both using the ast-types package. But it was easier to do this work using the estraverse package.

  • deprecated version 1

This first version using the library can only translate the rest element from a function with two parameters, one of which is the rest element. It cannot read multiple sentences. It only reads function declarations statemets.

import { parse } from "espree";
import { NodePath } from "ast-types";
import { namedTypes as n, builders as b, visit } from "ast-types";
import recast from "recast";
import * as espree from  "espree";

'use strict';

function spreadOperator(code) {

	let programPath = new NodePath(parse(code, { ecmaVersion: 6, loc: false }));
	let functionDeclaration = programPath.get("body", 0);

	let paramsLength = functionDeclaration.value.params.length;
	let varId = functionDeclaration.value.params[paramsLength - 1].argument.name;
	let lineToAdd = `let ${varId} = Array.prototype.slice.call(arguments, 1);`;
	let newNode = espree.parse(lineToAdd, {ecmaVersion: 6, loc: false}).body[0];
	delete(functionDeclaration.value.params[paramsLength - 1]);
	functionDeclaration.value.params = [functionDeclaration.value.params[0]];
	
	functionDeclaration.value.body.body.unshift(newNode)
	
	const resultCode = recast.print(programPath).code;

	return resultCode;

}
  • deprecated version 2

This second version as the irst one, can only translate rest elements.But in this case it visits all the nodes in the AST so it accepts multiple sentences and other things like nested functions declarations.

import { parse } from "espree";
import { NodePath } from "ast-types";
import { namedTypes as n, builders as b, visit } from "ast-types";
import recast from "recast";
import * as espree from  "espree";

'use strict';

function spreadOperator(code) {
  let ast = espree.parse(code, {ecmaVersion: 7, loc: false});


  let sliceExpr = b.memberExpression(
    b.memberExpression(            
      b.memberExpression(        
        b.identifier("Array"),    
        b.identifier("prototype"), 
        false
      ),
      b.identifier("slice"),       
      false
    ),
    b.identifier("call"),     
    false
  );

  visit(ast, {
    visitFunction(path) {
      const node = path.node;
      this.traverse(path);

      let lastArg = node.params.pop(); // Remove the 'rest' parameter
      if (lastArg.type !== "RestElement") return;
      
      // For the purposes of this example, we won't worry about functions
      // with Expression bodies.
      n.BlockStatement.assert(node.body);

      //   var rest = Array.prototype.slice.call(arguments, n);
      const restVarDecl = b.variableDeclaration("var", [
        b.variableDeclarator(
          lastArg.argument,
          b.callExpression(sliceExpr, [
            b.identifier("arguments"),
            b.literal(node.params.length)
          ])
        )
      ]);
    
      // Insert the statement 'var rest = Array.prototype.slice.call(arguments, n);' 
      // at the beginning of the body
      path.get("body", "body").unshift(restVarDecl);
      
    }
  });

  return recast.print(ast).code;
}

Examples

Here is an example of the execution of a very simple code where we to translate first a rest element from a function and then another exmple with the translation of an spread element in an array. These are the cases that this code can translate.

  • Example for rest element:

Input file:

var y = 1;
function sum(x, y, z, ...rest) {
  let b = x + y + z + rest[0];
  return b * rest[1];
}

Output:

var y = 1;
function sum(x, y, z) {
    var rest = Array.prototype.slice.call(arguments, 3);
    let b = x + y + z + rest[0];
    return b * rest[1];
}
  • Example for spread element:

Input file:

let parts = ['shoulders', 'knees'];
let lyrics = ['head', ...parts, 'and', 'toes'];

Output:

let parts = [
    'shoulders',
    'knees'
];
let lyrics = [].concat(['head'], parts, ['and'], ['toes']);

Author

Aram Pérez Dios alu0101244488