Skip to content

Commit

Permalink
fix(function-tree): fix name extraction for functions (#970)
Browse files Browse the repository at this point in the history
Use Function.name property if available. Support async functions and functions from shorthand syntax when extracting the name.
  • Loading branch information
sladiri authored and Guria committed Jun 21, 2017
1 parent 629c364 commit 73ce5de
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
9 changes: 8 additions & 1 deletion packages/node_modules/function-tree/src/staticTree.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,15 @@ import { Sequence, Parallel, Primitive } from './primitives'
import { FunctionTreeError } from './errors'

function getFunctionName(fn) {
if (fn.name) return fn.name

let ret = fn.toString()
ret = ret.substr('function '.length)

let startNameMatch
if (ret.startsWith('async function')) startNameMatch = 'async function '
else if (ret.startsWith('function')) startNameMatch = 'function '

ret = ret.substr(startNameMatch ? startNameMatch.length : 0)
ret = ret.substr(0, ret.indexOf('('))

return ret
Expand Down
5 changes: 3 additions & 2 deletions packages/node_modules/function-tree/src/staticTree.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,13 @@ import assert from 'assert'

describe('StaticTree', () => {
it('should create a static tree of an array', () => {
const tree = staticTree([function test() {}])
const tree = staticTree([function test() {}, { shortHand() {} }.shortHand])

assert.equal(tree.items.length, 1)
assert.equal(tree.items.length, 2)
assert.equal(tree._functionTreePrimitive, true)
assert.equal(tree.type, 'sequence')
assert.equal(tree.items[0].name, 'test')
assert.equal(tree.items[1].name, 'shortHand')
assert.equal(tree.items[0].functionIndex, 0)
assert.ok(tree.items[0].function)
})
Expand Down

0 comments on commit 73ce5de

Please sign in to comment.