{"id":13218,"library":"generate-function","title":"Dynamic Function Generator","description":"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()`.","status":"maintenance","version":"2.3.1","language":"javascript","source_language":"en","source_url":"https://github.com/mafintosh/generate-function","tags":["javascript","generate","code","generation","function","performance"],"install":[{"cmd":"npm install generate-function","lang":"bash","label":"npm"},{"cmd":"yarn add generate-function","lang":"bash","label":"yarn"},{"cmd":"pnpm add generate-function","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The library primarily uses CommonJS `require` syntax. Direct ES Module `import` is not officially supported without a transpiler or wrapper.","wrong":"import genfun from 'generate-function'","symbol":"genfun","correct":"const genfun = require('generate-function')"},{"note":"The `d` helper for safe data interpolation is accessed via the `formats` property of the main export.","wrong":"import { d } from 'generate-function/formats'","symbol":"d","correct":"const { d } = require('generate-function').formats"},{"note":"When your generated function needs to access variables from its creation scope, they must be explicitly passed as an object to `toFunction(scope)`.","wrong":"gen.toFunction() // when closing over variables","symbol":"toFunction","correct":"gen.toFunction(scope)"}],"quickstart":{"code":"const genfun = require('generate-function');\n\nfunction createDynamicAdder(baseValue) {\n  const gen = genfun();\n  const { d } = genfun.formats; // For safe data interpolation\n\n  // Generate a unique variable name for internal use\n  const tempVar = gen.sym('result');\n\n  gen(`\n    function (input) {\n      if (typeof input !== 'number') {\n        throw new Error('Input must be a number');\n      }\n      const ${tempVar} = input + ${d(baseValue)};\n      return ${tempVar};\n    }\n  `);\n\n  // Optional: pass variables to close over, e.g., for complex operations\n  // For this simple example, no external scope is strictly needed.\n  const dynamicAddFunc = gen.toFunction(); \n\n  console.log('Generated function source:\\n' + dynamicAddFunc.toString());\n  return dynamicAddFunc;\n}\n\nconst add5 = createDynamicAdder(5);\nconsole.log('10 + 5 =', add5(10));\nconsole.log('20 + 5 =', add5(20));\n\nfunction createScopedMultiplier(factor) {\n  const gen = genfun();\n  const { d } = genfun.formats;\n\n  // Define a helper function that the generated code will call\n  const multiplyHelper = (a, b) => a * b;\n\n  gen(`\n    function (value) {\n      if (typeof value !== 'number') {\n        throw new Error('Value must be a number');\n      }\n      // Call the 'multiplyHelper' from the scope passed to toFunction\n      return multiplyHelper(${d(factor)}, value);\n    }\n  `);\n\n  // Pass multiplyHelper into the scope of the generated function\n  const scopedMultiplyFunc = gen.toFunction({ multiplyHelper });\n\n  console.log('\\nGenerated scoped function source:\\n' + scopedMultiplyFunc.toString());\n  return scopedMultiplyFunc;\n}\n\nconst multiplyBy3 = createScopedMultiplier(3);\nconsole.log('4 * 3 =', multiplyBy3(4));","lang":"javascript","description":"This quickstart demonstrates creating dynamic functions, interpolating values safely, generating unique variable names, and closing over external variables using `toFunction(scope)`."},"warnings":[{"fix":"Thoroughly test generated functions, validate all inputs, and use `gen.sym()` and `gen.property()` for safe identifier and property access within generated code.","message":"Generating code dynamically is complex and should primarily be used for performance-critical scenarios where static code generation significantly improves execution speed (e.g., schema validators, parsers). Misuse can lead to difficult-to-debug issues and potential security vulnerabilities if input is not carefully sanitized.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"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.","message":"Security vulnerability due to improper input sanitization when concatenating user-provided strings directly into the generated function's source can lead to arbitrary code execution (injection attacks).","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"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 })`.","message":"When closing over variables, ensure all necessary external references are explicitly passed in the scope object to `toFunction(scope)`. Variables not in the scope or not globally accessible will result in `ReferenceError`s at runtime.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Ensure `someVariable` is either defined directly in the generated source or is included in the object passed to `gen.toFunction({ someVariable })`.","cause":"The generated function attempts to access a variable (e.g., `someVariable`) that was not defined within its own generated scope and was not passed in the `scope` object to `gen.toFunction()`.","error":"ReferenceError: someVariable is not defined"},{"fix":"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.","cause":"The string passed to `gen()` contains invalid JavaScript syntax, often due to incorrect concatenation, unescaped characters, or malformed template literals.","error":"SyntaxError: Unexpected token '...' (or similar parsing error)"},{"fix":"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.","cause":"The `generate-function` module primarily exports a CommonJS module with `module.exports = function (...)`. When used with ES Modules, `import genfun from 'generate-function'` might attempt a default import where there isn't one, or it might incorrectly interpret the export.","error":"TypeError: genfun is not a function (when using `import genfun from 'generate-function'`)"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":""}