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

js-code-generator

v1.0.1

Published

Programmatically generate javascript

Downloads

843

Readme

CodeGenerator

Programmatically generate javascript.

Usage

npm install js-code-generator

Features

  • Handles code indentation for you while allowing you to set the number of spaces and tabs.
  • Provides helper method to generate unique names for iterator variables to make generating nested loops easier
  • consistent function arguments and return values

Example

var Generate = require("./CodeGenerator.js");

var itrVar = Generate.variable({
  name: Generate.uniqueIteratorName(),
  value: "0"
});

var code =
  Generate.forLoop({
    startCondition: `${itrVar.data.name} = 0`,
    stopCondition: `${itrVar.data.name} < 10`,
    incrementAction: `${itrVar.data.name} += 1`,
    body: function() {
      return Generate.ifStatement({
        condition: `${itrVar.data.name} % 2 == 0`,
        body: function() {
          return Generate.consoleLog(["'even'"]).code;
        }
      }).code
    }
  }).code
  
console.log(code);

/* Output:
for (var i = 0; i < 10; i += 1) {
  if (i % 2 == 0) {
    console.log("even");
  }
}
*/

Config

numSpacesPerTab (defaults to 4)

The number of spaces that make up 1 tab. Used for code indentation.

CodeGenerator.numSpacesPerTab = 2;

numTabs (defaults to 1)

The number of spaces that make up 1 tab. Used for code indentation.

CodeGenerator.numTabs = 2;

Methods

variable

/*
  @param Object data {
    {string} name,
    {string} value (optional)
  }
  
  @returns {
    data: data,
    code: code
  } 
*/

var example1 = Generate.variable({name: "test", value: "0"});
console.log(example1.code)
// var test = 0;

var example2 = Generate.variable({name: "test"});
console.log(example2.code)
// var test;

reassignVariable

/*
  @param Object data {
    {string} name,
    {string} value
  }
  
  @returns {
    data: data,
    code: code
  } 
*/


var code = [];

var testVar = Generate.variable({name: "test"});
code.push(testVar.code);

var example = Generate.reassignVariable({name: testVar.data.name, value: "0"})
code.push(example.code);

console.log(code.join("\n"));

/* Output:
var test;
test = 0;
*/

incrementVariable

/*
@param Object data {
  {string} name,
  {function} value (Optional)
}
*/


var code = [
  Generate.variable(name: "num", value: "0").code, 
  Generate.incrementVariable({name: numVar.data.name, value: "4"}).code,
  Generate.incrementVariable({name: numVar.data.name}).code,
]

console.log(code.join("\n"));

/* Output:
var num = 0;
num += 4;
num++
*/

decrementVariable

/*
@param Object data {
  {string} name,
  {function} value (Optional)
}
*/


var code = [
  Generate.variable(name: "num", value: "0").code, 
  Generate.decrementVariable({name: numVar.data.name, value: "4"}).code,
  Generate.decrementVariable({name: numVar.data.name}).code,
]

console.log(code.join("\n"));

/* Output:
var num = 0;
num -= 4;
num--
*/

firstClassFunction

/*
  @param Object data {
    {string} name,
    {array} args (Optional),
    {function} body
  }
  @returns {
    data: data,
    code: code
  } 
*/

var example = Generate.firstClassFunction({
  name: "func",
  args: ["a", "b", "c"],
  body: function() {
    return Generate.consoleLog("hi").code;
  }
})

console.log(example.code)

/* Output:
var func = function(a, b, c) {
  console.log("hi");
};
*/

newInstance

  /*
    @param Object data {
      {string} type
      {array} args
    }

    @returns Object {
      {string} code
    }
  */

  var instance = Generate.newInstance({type: "Person", args: ["'Bob'", 30]});
  var personVar = Generate.variable({name: "person", value: instance.code});
  console.log(personVar.code);

  /* Output:
    var person = new Person('Bob', 30);
  */

objectPropertyAssignment

/*
  @param Object data {
    {string} objName (Optional. Defaults to "this")
    {string} propName,
    {string} value,
    {boolean} dotNotation (Optional. Defaults to true)
  }
*/


var objVar = Generate.variable({
  name: "obj",
  value: {}
});

var example1 = Generate.objectPropertyAssignment({
  objName: objVar.data.name, 
  propName: "prop",
  value: "hello"
});

var example2 = Generate.objectPropertyAssignment({
  objName: objVar.data.name, 
  propName: "prop",
  value: "hello",
  dotNotation: false
});

var code = [
  objVar.code,
  example1.code,
  example2.code
].join("\n")

console.log(code);

/* Output:
var obj = {};
obj.prop = "hello";
obj["prop"] = "hello";
*/

objectFunctionCall

/*
  @param Object data {
    {string} objName (Optional. Defaults to "this")
    {string} funcName,
    {array} args (Optional)
  }
*/

var example = Generate.objectFunctionCall({
  objName: "Math",
  funcName: "floor",
  args: [3.5]
})

console.log(example.code);

/* Output:
Math.floor(3.5);
*/

objectFunction

/*
  @param Object data {
    {string} objName (Optional. Defaults to "this")
    {string} funcName,
    {array} args (Optional),
    {function} body
  }
*/

var example = Generate.objectFunction({
  objName: "obj",
  funcName: "sumNums",
  args: ["nums"],
  body: function() {
    return Generate.comment({text: "code to sum elements of nums array"}).code
  }
})

console.log(example.code);

/* Output:
obj.sumNums = function(nums) {
  // code to sum elemens of nums array 
}
*/

ifStatement

/*
@param Object data {
  {string} condition,
  {function} body
}
*/

var numVar = Generate.variable(name: "num", value: "0");

var example = Generate.ifStatement({
  condition: `${numVar.data.name} > 2`,
  body: function() {
    let body = [
      Generate.incrementVariable({name: numVar.data.name, value: "4"}).code,
      Generate.incrementVariable({name: numVar.data.name}).code,
    ];

    return body.join("\n");
  }
});

var code = [
  numVar.code,
  example.code
].join("\n");

console.log(code)

/* Output:
var num = 0;
if (num > 2) {
  numVar += 4;
  numVar++
}
*/

elseIfStatement

elseStatement

tryBlock

catchBlock

forLoop

/*
  @param Object data {
    {string} startCondition,
    {string} stopCondition,
    {string} incrementAction,
    {function} body
  }
*/

var nestedForLoop = 
  Generate.forLoop({
    startCondition: `${itrVar.data.name} = 0`,
    stopCondition: `${itrVar.data.name} < 10`,
    incrementAction: `${itrVar.data.name} += 1`,
    body: function() {
      let itrVar = Generate.variable({
        name: Generate.uniqueIteratorName(),
        value: "0"
      });

      return (
        Generate.forLoop({
          startCondition: `${itrVar.data.name} = 0`,
          stopCondition: `${itrVar.data.name} < 10`,
          incrementAction: `${itrVar.data.name} += 1`,
          body: function() {
            let itrVar = Generate.variable({
              name: Generate.uniqueIteratorName(),
              value: "0"
            });

            return (
              Generate.forLoop({
                startCondition: `${itrVar.data.name} = 0`,
                stopCondition: `${itrVar.data.name} < 10`,
                incrementAction: `${itrVar.data.name} += 1`,
                body: function() {
                  return "";
                }
              }).code
            )
          }
        }).code
      )
    }
  }).code

console.log(nestedForLoop);

/* Output:
for (var i = 0; i < 10; i += 1) {
  for (var j = 0; j < 10; j += 1) {
    for (var k = 0; k < 10; k += 1) {

    }
  }
}
*/