Skip to content

Instantly share code, notes, and snippets.

@ebeloded
Last active July 30, 2021 23:33
Show Gist options
  • Save ebeloded/27a9f6387665d026910e0e984d1bf47a to your computer and use it in GitHub Desktop.
Save ebeloded/27a9f6387665d026910e0e984d1bf47a to your computer and use it in GitHub Desktop.
getFunctionParams
/**
* Returns parameters of a function
* Works for anonymous and named functions
* @param {Function} func
*/
const getFunctionParams = (func: Function): string[] =>
new RegExp('(?:\\s*|^)\\s*\\((.*?)\\)')
.exec(func.toString().replace(/\n/g, ''))![1]
.replace(/\/\*.*?\*\//g, '')
.replace(/ /g, '')
.split(',')
export default getFunctionParams
/*
function myFunction(x: number, z: string) {
return { x, z, a, b }
}
const fun = (y: string) => {
return y
}
getFunctionParams(myFunction) // [ 'x', 'z' ]
getFunctionParams(fun) // [ 'y']
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment