generate-function is a specialized Node.js utility designed to assist in creating dynamic JavaScript functions programmatically. Its primary use case is in scenarios demanding extreme performance optimization, such as constructing schema validators or parsers where static code generation can significantly reduce runtime overhead. The library is currently at version 2.3.1. It maintains a stable, low-cadence release schedule, as it addresses a specific, mature problem domain. A key differentiator is its focus on robust, safe code generation primitives like `gen.sym()` for unique identifiers and `gen.property()` for safe property access, which abstract away common pitfalls of manual string concatenation for code. It provides methods to append source code incrementally and to close over external variables safely by passing a scope object to `toFunction()`.
npm install generate-functionVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates creating dynamic functions, interpolating values safely, generating unique variable names, and closing over external variables using `toFunction(scope)`.
Thoroughly test generated functions, validate all inputs, and use `gen.sym()` and `gen.property()` for safe identifier and property access within generated code.
Always use `gen.formats.d()` for data interpolation to ensure values are correctly serialized and escaped. Avoid direct string concatenation of untrusted input into `gen()` calls. Only pass trusted, pre-validated values.
Review the generated function's source (`gen.toString()`) to identify missing variables. Pass all required external variables as properties of an object to `gen.toFunction({ var1, var2 })`.Ensure `someVariable` is either defined directly in the generated source or is included in the object passed to `gen.toFunction({ someVariable })`.Carefully review the source string passed to `gen()` and `gen.formats.d()` calls. Use `gen.toString()` to inspect the complete generated function source code and identify the syntax error.
Use the CommonJS `require` syntax: `const genfun = require('generate-function');` in Node.js environments. If using ES Modules, you might need `import * as genfun from 'generate-function'` or configure your build tool to handle CJS interop correctly.No dependency data recorded yet.