Security News
The Dark Side of Open Source
At Node Congress, Socket CEO Feross Aboukhadijeh uncovers the darker aspects of open source, where applications that rely heavily on third-party dependencies can be exploited in supply chain attacks.
generate-function
Advanced tools
Package description
The generate-function package is a tool for creating dynamic functions in JavaScript. It allows developers to programmatically build new functions as strings and then compile them into executable functions. This can be particularly useful for cases where you need to generate custom logic at runtime based on certain conditions, or when you want to optimize performance by compiling a function once and reusing it multiple times.
Creating a simple function
This feature allows you to create a simple function that returns a static value. The code sample demonstrates generating a function that returns the number 42.
var gen = require('generate-function');
var fn = gen()
.body('return 42;')
.toFunction();
console.log(fn()); // 42
Creating a function with parameters
This feature allows you to create a function with parameters. The code sample demonstrates generating a function that takes two parameters and returns their sum.
var gen = require('generate-function');
var fn = gen()
.param('a', 'b')
.body('return a + b;')
.toFunction();
console.log(fn(1, 2)); // 3
Creating a function with a complex body
This feature allows you to create a function with a more complex body, including logic and control structures. The code sample demonstrates generating a function that compares two values and returns the larger one.
var gen = require('generate-function');
var fn = gen()
.body('if (a > b) { return a; } else { return b; }')
.toFunction();
console.log(fn(5, 3)); // 5
The new-function package is similar to generate-function in that it allows you to create new functions from strings. However, it does not provide the same level of API for building the function body and parameters programmatically.
The function-plot package is designed for plotting mathematical functions and does not directly compete with generate-function. However, it can be used in conjunction with generate-function to dynamically create and plot functions.
Escodegen is a code generator for ECMAScript. It's more general-purpose than generate-function, as it can generate code for entire programs or AST nodes, not just functions. It's more complex and powerful but also has a steeper learning curve.
Readme
Module that helps you write generated functions in Node
npm install generate-function
Writing code that generates code is hard. You should only use this if you really, really, really need this for performance reasons (like schema validators / parsers etc).
const genfun = require('generate-function')
const { d } = genfun.formats
function addNumber (val) {
const gen = genfun()
gen(`
function add (n) {')
return n + ${d(val)}) // supports format strings to insert values
}
`)
return gen.toFunction() // will compile the function
}
const add2 = addNumber(2)
console.log('1 + 2 =', add2(1))
console.log(add2.toString()) // prints the generated function
If you need to close over variables in your generated function pass them to toFunction(scope)
function multiply (a, b) {
return a * b
}
function addAndMultiplyNumber (val) {
const gen = genfun()
gen(`
function (n) {
if (typeof n !== 'number') {
throw new Error('argument should be a number')
}
const result = multiply(${d(val)}, n + ${d(val)})
return result
}
`)
// use gen.toString() if you want to see the generated source
return gen.toFunction({multiply})
}
const addAndMultiply2 = addAndMultiplyNumber(2)
console.log(addAndMultiply2.toString())
console.log('(3 + 2) * 2 =', addAndMultiply2(3))
You can call gen(src)
as many times as you want to append more source code to the function.
If you need a unique safe identifier for the scope of the generated function call str = gen.sym('friendlyName')
.
These are safe to use for variable names etc.
If you need to access an object property use the str = gen.property('objectName', 'propertyName')
.
This returns 'objectName.propertyName'
if propertyName
is safe to use as a variable. Otherwise
it returns objectName[propertyNameAsString]
.
If you only pass gen.property('propertyName')
it will only return the propertyName
part safely
MIT
FAQs
Module that helps you write generated functions in Node
The npm package generate-function receives a total of 2,998,325 weekly downloads. As such, generate-function popularity was classified as popular.
We found that generate-function demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
At Node Congress, Socket CEO Feross Aboukhadijeh uncovers the darker aspects of open source, where applications that rely heavily on third-party dependencies can be exploited in supply chain attacks.
Research
Security News
The Socket Research team found this npm package includes code for collecting sensitive developer information, including your operating system username, Git username, and Git email.
Security News
OpenJS is warning of social engineering takeovers targeting open source projects after receiving a credible attempt on the foundation.