3 Module that helps you write generated functions in Node
6 npm install generate-function
9 [![build status](http://img.shields.io/travis/mafintosh/generate-function.svg?style=flat)](http://travis-ci.org/mafintosh/generate-function)
13 Writing code that generates code is hard.
14 You should only use this if you really, really, really need this for performance reasons (like schema validators / parsers etc).
19 var genfun = require('generate-function')
21 var addNumber = function(val) {
24 ('return n + %d', val) // supports format strings to insert values
27 return fn.toFunction() // will compile the function
30 var add2 = addNumber(2)
32 console.log('1+2=', add2(1))
33 console.log(add2.toString()) // prints the generated function
36 If you need to close over variables in your generated function pass them to `toFunction(scope)`
39 var multiply = function(a, b) {
43 var addAndMultiplyNumber = function(val) {
46 ('if (typeof n !== "number") {') // ending a line with { will indent the source
47 ('throw new Error("argument should be a number")')
49 ('var result = multiply(%d, n+%d)', val, val)
53 // use fn.toString() if you want to see the generated source
55 return fn.toFunction({
60 var addAndMultiply2 = addAndMultiplyNumber(2)
62 console.log('(3 + 2) * 2 =', addAndMultiply2(3))
67 See [generate-object-property](https://github.com/mafintosh/generate-object-property) if you need to safely generate code that
68 can be used to reference an object property