2.3.1 • Published 6 years ago

generate-function v2.3.1

Weekly downloads
2,012,947
License
MIT
Repository
github
Last release
6 years ago

generate-function

Module that helps you write generated functions in Node

npm install generate-function

build status

Disclamer

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).

Usage

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.

Variables

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.

Object properties

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

License

MIT

is-my-json-validkemand@everything-registry/sub-chunk-1731@gadgetinc/graphql-jit@gazatu/graphql-jitweb-component-tester-bundlewc-starterkittrevorlinton-jsonpath-faster@hoangvvo/graphql-jitreact-mysql3react-formsroad-markingtoyakoshared-structssolregex2stella-json-validatortcomb-codectypeorm-polymorphic-clonetypographic-orphanturbo-json-parsevcloudcam-playkit-js-hlswow.js-juzieslint-plugin-aurelia-event-aggregatorfahad-redux-axios-midlewarefd-proxy-serverfast-date-parsefec-parsefenglin-uploaderdwa-csv-parser@inovando-boletos/boleto@infinitebrahmanuniverse/nolb-generategraphql-jitgost-mysql@mblode/react-native-featherfirst-app-lyfuci@mattersmedia/html-to-article-jsonfast-translationfastify-access-loggergenerate-compare-functiongenerate-radix-tree@kingworldjs/graphql-jiteyeq-csv-parser@ishikawa-pro/mysql2hue-binary-data@rgbboy/is-my-json-validhw9@rstacruz/pnpm@easycancha/mysql2html-to-article-json@schacker/hpack-cli@seydx/binary-data@shinyoshiaki/binary-data@shiyuhang0/mysql2is-my-json-valid-custom-errjsonpath-faster@the91end/react-authklaru-mysql-wrapperklikrouter@bigfishtv/react-formsbon-etat@bahmutov/is-my-json-validaxios-retry-anomysql4mysql2mysql2-degfy-testmysql2-stream-fix@vlasky/mysql2@cweijan/mysql2@circuitly/mysql2node-dorisbinary-data@coorpacademy/mysql2npm-all-packages@zhennann/mysql2@weo-edu/validate2dpixels-canvas@vdtn359/graphql-jitmiguelcostero-ng2-toastyka-flow.jsapc-youtube@cdevine49/react-numeric-inputpbsplaykit-js-hls-sondq@deskpro/react-formscombiner-libcordova-plugin-amplify-paycordova-plugin-amplify-paymentcordova-plugin-tsppixel-to-css-colorpixels-canvasprotocol-buffersdigital-keyboard-demosdoris2
2.3.1

6 years ago

2.3.0

6 years ago

2.2.1

6 years ago

2.2.0

6 years ago

2.0.0

10 years ago

1.1.0

10 years ago

1.0.3

10 years ago

1.0.2

10 years ago

1.0.1

10 years ago

1.0.0

10 years ago

0.0.0

10 years ago