Security update for permissions_by_term
[yaffs-website] / node_modules / generate-function / README.md
1 # generate-function
2
3 Module that helps you write generated functions in Node
4
5 ```
6 npm install generate-function
7 ```
8
9 [![build status](http://img.shields.io/travis/mafintosh/generate-function.svg?style=flat)](http://travis-ci.org/mafintosh/generate-function)
10
11 ## Disclamer
12
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).
15
16 ## Usage
17
18 ``` js
19 var genfun = require('generate-function')
20
21 var addNumber = function(val) {
22   var fn = genfun()
23     ('function add(n) {')
24       ('return n + %d', val) // supports format strings to insert values
25     ('}')
26
27   return fn.toFunction() // will compile the function
28 }
29
30 var add2 = addNumber(2)
31
32 console.log('1+2=', add2(1))
33 console.log(add2.toString()) // prints the generated function
34 ```
35
36 If you need to close over variables in your generated function pass them to `toFunction(scope)`
37
38 ``` js
39 var multiply = function(a, b) {
40   return a * b
41 }
42
43 var addAndMultiplyNumber = function(val) {
44   var fn = genfun()
45     ('function(n) {')
46       ('if (typeof n !== "number") {') // ending a line with { will indent the source
47         ('throw new Error("argument should be a number")')
48       ('}')
49       ('var result = multiply(%d, n+%d)', val, val)
50       ('return result')
51     ('}')
52
53   // use fn.toString() if you want to see the generated source
54
55   return fn.toFunction({
56     multiply: multiply
57   })
58 }
59
60 var addAndMultiply2 = addAndMultiplyNumber(2)
61
62 console.log('(3 + 2) * 2 =', addAndMultiply2(3))
63 ```
64
65 ## Related
66
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
69
70 ## License
71
72 MIT