Created
January 26, 2018 12:10
-
-
Save scagood/9b2f6462ed06815de2f020a80e7ba506 to your computer and use it in GitHub Desktop.
Provides a simple function to get the arguments of a function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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