Skip to content

Instantly share code, notes, and snippets.

@scagood
Created January 26, 2018 12:10
Show Gist options
  • Save scagood/9b2f6462ed06815de2f020a80e7ba506 to your computer and use it in GitHub Desktop.
Save scagood/9b2f6462ed06815de2f020a80e7ba506 to your computer and use it in GitHub Desktop.
Provides a simple function to get the arguments of a function
function getArgs(func) {
/**
* Basic function regex
* - /^function\s*\w*\(([\w\W]*?)\)\s*{/
*
* Arrow function regex
* - /^([^()]*)\s*=>/
* - /^\(([\w\W]*?)\)\s*=>/
* */
if (typeof func !== 'function') {
throw new TypeError(
'Function expected, recieved: "' + typeof func + '"'
);
}
// First match everything inside the function argument parens.
func = func.toString();
const args = (
// Try default functions
func.match(/^function\s*\w*\(([\w\W]*?)\)\s*{/) ||
// Try single arg arrows
func.match(/^([^()]*)\s*=>/) ||
// Try multiple args arrows
func.match(/^\(([\w\W]*?)\)\s*=>/)
)[1];
return args
// Remove comments
.replace(/\/\*.*?\*\//g, '')
// Remove excess space
.replace(/\s+/g, ' ')
// Into arguments
.split(',')
// Remove assertions
.map(arg => arg.split('=').shift().trim())
// Remove false positive args
.filter(arg => arg);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment