-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
61 lines (53 loc) · 1.65 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*!
* function-arguments <https://github.com/tunnckoCore/function-arguments>
*
* Copyright (c) 2016 Charlike Mike Reagent <@tunnckoCore> (http://www.tunnckocore.tk)
* Released under the MIT license.
*/
'use strict'
/**
* > Get function arguments names.
*
* **Example**
*
* ```js
* var fnArgs = require('function-arguments')
*
* console.log(fnArgs(function (a, b, c) {})) // => [ 'a', 'b', 'c' ]
* console.log(fnArgs(function named (a , b, c) {})) // => [ 'a', 'b', 'c' ]
*
* console.log(fnArgs(a => {})) // => [ 'a' ]
* console.log(fnArgs((a, b) => {})) // => [ 'a', 'b' ]
*
* console.log(fnArgs(function * (a ,b, c) {})) // => [ 'a', 'b', 'c' ]
* console.log(fnArgs(function * named (a ,b, c) {})) // => [ 'a', 'b', 'c' ]
* ```
*
* @param {Function} `fn` Function from which to get arguments names.
* @return {Array}
* @api public
*/
module.exports = function functionArguments (fn) {
if (typeof fn !== 'function') {
throw new TypeError('function-arguments expect a function')
}
if (fn.length === 0) {
return []
}
// from https://github.com/jrburke/requirejs
var reComments = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg
var fnToStr = Function.prototype.toString
var fnStr = fnToStr.call(fn)
fnStr = fnStr.replace(reComments, '') || fnStr
fnStr = fnStr.slice(0, fnStr.indexOf('{'))
var open = fnStr.indexOf('(')
var close = fnStr.indexOf(')')
open = open >= 0 ? open + 1 : 0
close = close > 0 ? close : fnStr.indexOf('=')
fnStr = fnStr.slice(open, close)
fnStr = '(' + fnStr + ')'
var match = fnStr.match(/\(([\s\S]*)\)/)
return match ? match[1].split(',').map(function (param) {
return param.trim()
}) : []
}