build-ast
Make build AST nodes easy
Install
$ npm install [--save] @helpdotcom/build-ast
Test
$ npm test
Example
'use strict'
const B = require('@helpdotcom/build-ast')
const toCode = require('escodegen').generate
const b = B().use('strict')
const left = B.typeof('opts.name')
const right = B.string('string')
const check = B.notEquals(left, right)
const error = B.TypeError('name must be a string')
const errorBlock = B()
.declare('const', 'er', error)
.returns(
B.callFunction('setImmediate', [
B.id('cb')
, B.id('er')
])
).build()
const block = B()
block.if(check, B.block(errorBlock))
block.returns(
B.callFunction('setImmediate', [
B.id('cb')
, B.ast.literal(null)
, B.id('opts')
])
)
b.module(B.function('validate', ['opts', 'cb'], block.build()))
console.log(toCode(b.program()))
which will print out:
'use strict';
module.exports = function validate(opts, cb) {
if (typeof opts.name !== 'string') {
const er = new TypeError('name must be a string')
return setImmediate(cb, er)
}
return setImmediate(cb, null, opts)
}
API
See DOCS.md
Author
Evan Lucas
License
MIT (See LICENSE
for more info)