JSPM

  • Created
  • Published
  • Downloads 165691
  • Score
    100M100P100Q158563F
  • License MIT

Parse a function to an object that has its name, body, args and few more useful properties. Support regular functions, async/await, arrow and generator functions.

Package Exports

  • parse-function

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (parse-function) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

parse-function NPM version NPM downloads npm total downloads

Parse a function to an object that has its name, body, args and few more useful properties. Support regular functions, async/await, arrow and generator functions.

code climate standard code style linux build status windows build status coverage status dependency status

Pro Tips (What version to use?)

There's no breaking changes between versions, the only version that have partial breaking change is v2.1.x, so don't use it.

  • use v2.0.x - if you don't need support for arrow functions and es6 default params.
  • use v2.2.x - if you just want basic support for es6 features like ES6 Arrow Functions (faster than v2.3.x)
  • use v2.3.x - if you want full support of es6 arrow functions and es6 default params (this uses acorn)
  • use v3 if you want to want to use custom parser instead of babylon default one (same speed as v2.3.x)

Run the benchamrks to see the diffs. The v2.0.x is the fastest one, but it has lack of features. The v2.3.x versions has some bugs. And the v3 has ability to customize the parser and can pass options directly to the parser.

Table of Contents

(TOC generated by verb using markdown-toc)

Install

Install with npm

$ npm install parse-function --save

or install using yarn

$ yarn add parse-function

Usage

For more use-cases see the tests

const parseFunction = require('parse-function')

API

parseFunction

Parse a function or string that contains a function, using babylon or acorn parsers. By default it uses babylon, but you can pass custom one through options.parse option - for example pass .parse: acorn.parse to force use the acorn parser instead.

Params

  • code {Function|String}: function to be parsed, it can be string too
  • options {Object}: optional, passed directly to babylon or acorn
  • options.parse {Function}: custom parse function passed with code and options
  • returns {Object}: always returns an object, see result section

Example

const parseFunction = require('parse-function')

const myFn = function abc (e, f, ...rest) { return 1 + e + 2 + f }
const parsed = parseFunction(myFn)

console.log(parsed.name) // => 'abc'
console.log(parsed.body) // => ' return 1 + e + 2 + f '
console.log(parsed.args) // => [ 'e', 'f', 'rest' ]
console.log(parsed.params) // => 'e, f, rest'

// some useful `is*` properties
console.log(parsed.isValid) // => true
console.log(parsed.isNamed) // => true
console.log(parsed.isArrow) // => false
console.log(parsed.isAnonymous) // => false
console.log(parsed.isGenerator) // => false

// use `acorn` parser
const acorn = require('acorn')
const someArrow = (foo, bar) => 1 * foo + bar
const result = parseFunction(someArrow, {
  parse: acorn.parse,
  ecmaVersion: 2017
})

console.log(result.name) // => 'anonymous'
console.log(result.body) // => '1 * foo + bar'
console.log(result.args) // => [ 'foo', 'bar' ]

console.log(result.isValid) // => true
console.log(result.isArrow) // => true
console.log(result.isNamed) // => false
console.log(result.isAnonymous) // => true

// or use "loose mode" of the acorn parser
const acornLoose = require('acorn/dist/acorn_loose')
const fooBarFn = async (a, b, ...c) => {
  return Promise.resolve([a, b].concat(c))
}
const res = parseFunction(fooBarFn, {
  parse: acornLoose.parse_dammit
})

console.log(res.body) // => '\n  return Promise.resolve([a, b].concat(c))\n'
console.log(res.args) // => ['a', 'b', 'c']
console.log(res.isValid) // => true
console.log(res.isAsync) // => true
console.log(res.isArrow) // => true
console.log(res.isNamed) // => false
console.log(res.isAnonymous) // => true

Result

In the result object you have name, args, params, body and few hidden properties that can be useful to determine what the function is - arrow, regular, async/await or generator.

It never throws! You should check result.isValid property.

  • name {String}: name of the passed function
  • args {Array}: arguments of the function
  • params {String}: comma-separated list representing the args
  • defaults {Object}: key/value pairs, useful when use ES2015 default arguments
  • body {String}: actual body of the function, respects trailing newlines and whitespaces
  • isValid {Boolean}: is the given value valid or not, that's because it never throws!
  • isAsync {Boolean}: true if function is ES2015 async/await function
  • isArrow {Boolean}: true if the function is arrow function
  • isNamed {Boolean}: true if function has name, or false if is anonymous
  • isGenerator {Boolean}: true if the function is ES2015 generator function
  • isAnonymous {Boolean}: true if the function don't have name
  • value {String}: string representation of the passed code argument
  • acorn: ECMAScript parser | homepage
  • always-done: Handle completion and errors with elegance! Support for streams, callbacks, promises, child processes, async/await and sync functions. A drop-in replacement… more | homepage
  • babylon: A JavaScript parser | homepage
  • each-promise: Iterate over promises, promise-returning or async/await functions in series or parallel. Support settle (fail-fast), concurrency (limiting) and hooks system (start… more | homepage
  • espree: An Esprima-compatible JavaScript parser built on Acorn | homepage
  • minibase: Minimalist alternative for Base. Build complex APIs with small units called plugins. Works well with most of the already existing… more | homepage
  • parse-semver: Parse, normalize and validate given semver shorthand (e.g. gulp@v3.8.10) to object. | homepage
  • try-catch-core: Low-level package to handle completion and errors of sync or asynchronous functions, using once and dezalgo libs. Useful for and… more | homepage

Contributing

Pull requests and stars are always welcome. For bugs and feature requests, please create an issue.
Please read the contributing guidelines for advice on opening issues, pull requests, and coding standards.
If you need some help and can spent some cash, feel free to contact me at CodeMentor.io too.

In short: If you want to contribute to that project, please follow these things

  1. Please DO NOT edit README.md, CHANGELOG.md and .verb.md files. See "Building docs" section.
  2. Ensure anything is okey by installing the dependencies and run the tests. See "Running tests" section.
  3. Always use npm run commit to commit changes instead of git commit, because it is interactive and user-friendly. It uses commitizen behind the scenes, which follows Conventional Changelog idealogy.
  4. Do NOT bump the version in package.json. For that we use npm run release, which is standard-version and follows Conventional Changelog idealogy.

Thanks a lot! :)

Building docs

Documentation and that readme is generated using verb-generate-readme, which is a verb generator, so you need to install both of them and then run verb command like that

$ npm install verbose/verb#dev verb-generate-readme --global && verb

Please don't edit the README directly. Any changes to the readme must be made in .verb.md.

Running tests

Clone repository and run the following in that cloned directory

$ npm install && npm test

Author

Charlike Mike Reagent

License

Copyright © 2016, Charlike Mike Reagent. Released under the MIT license.


This file was generated by verb-generate-readme, v0.2.0, on December 10, 2016.