2.3.4 • Published 7 years ago

@helpdotcom/build-ast v2.3.4

Weekly downloads
9
License
MIT
Repository
github
Last release
7 years ago

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

// 'use strict'
const b = B().use('strict')

// `typeof opts.name`
const left = B.typeof('opts.name')

// `'string'`
const right = B.string('string')

// `typeof opts.name !== 'string'`
const check = B.notEquals(left, right)

// new TypeError('name must be a string')
const error = B.TypeError('name must be a string')

// const er = new TypeError('name must be a string')
// return setImmediate(cb, er)
const errorBlock = B()
  .declare('const', 'er', error)
  .returns(
    B.callFunction('setImmediate', [
      B.id('cb')
    , B.id('er')
    ])
  ).build()

// if (typeof opts.name !== 'string') {
//   const er = new TypeError('name must be a string')
//   return setImmediate(cb, er)
// }
const block = B()
block.if(check, B.block(errorBlock))
block.returns(
  B.callFunction('setImmediate', [
    B.id('cb')
  , B.ast.literal(null)
  , B.id('opts')
  ])
)

// module.exports = function validate(opts, cb) {}
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)

2.3.4

7 years ago

2.3.3

7 years ago

2.3.2

7 years ago

2.3.1

8 years ago

2.3.0

8 years ago

2.2.0

8 years ago

2.1.0

8 years ago

2.0.0

8 years ago

1.5.0

8 years ago

1.4.4

8 years ago

1.4.3

8 years ago

1.4.2

8 years ago

1.4.1

8 years ago

1.4.0

8 years ago

1.3.0

8 years ago

1.2.0

8 years ago

1.1.0

8 years ago

1.0.0

8 years ago