Is there a way to get the function parameter names of a function dynamically?
Let’s say my function looks like this:
function doSomething(param1, param2, .... paramN){
// fill an array with the parameter name and value
// some other code
}
Now, how would I get a list of the parameter names and their values into an array from inside the function?
I don't know if this solution suits your problem, but it lets you redefine whatever function you want, without having to change code that uses it. Existing calls will use positioned params, while the function implementation may use "named params" (a single hash param).
I thought that you will anyway modify existing function definitions so, why not having a factory function that makes just what you want:
Hope it helps.
I have read most of the answers here, and I would like to add my one-liner.
or
or for a one-liner function in ECMA6
__
Let's say you have a function
The below code will return
"abc,def,ghi,jkl"
That code will also work with the setup of a function that Camilo Martin gave:
Also with Bubersson's comment on Jack Allan's answer:
__
Explanation
new RegExp(Function.name+'\\s*\\((.*?)\\)')
This creates a Regular Exponent with the
new RegExp(Function.name+'\\s*\\((.*?)\\)')
. I have to usenew RegExp
because I am injecting a variable (Function.name
, the name of the function being targeted) into the RegExp.Example If the function name is "foo" (
function foo()
), the RegExp will be/foo\s*\((.*?)\)/
.Function.toString().replace(/\n/g, '')
Then it converts the entire function into a string, and removes all newlines. Removing newlines helps with the function setup Camilo Martin gave.
.exec(...)[1]
This is the
RegExp.prototype.exec
function. It basically matches the Regular Exponent (new RegExp()
) into the String (Function.toString()
). Then the[1]
will return the first Capture Group found in the Regular Exponent ((.*?)
)..replace(/\/\*.*?\*\//g, '').replace(/ /g, '')
This will remove every comment inside
/*
and*/
, and remove all spaces.If you want to make all the parameters into an Array instead of a String separated by commas, at the end just add
.split(',')
.I've tried doing this before, but never found a praticial way to get it done. I ended up passing in an object instead and then looping through it.
This package uses recast in order to create an AST and then the parameter names are gathered from their, this allows it to support pattern matching, default arguments, arrow functions and other ES6 features.
https://www.npmjs.com/package/es-arguments
I'll give you a short example below:
Here is an updated solution that attempts to address all the edge cases mentioned above in a compact way:
Abbreviated test output (full test cases are attached below):