Created
February 19, 2012 18:30
-
-
Save naholyr/1865010 to your computer and use it in GitHub Desktop.
JS Introspection: extract function parameter names
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.prototype.argNames = function () { | |
// Extract function string representation: hopefully we can count on it ? | |
var s = this.toString(); | |
// The cool thing is: this can only be a syntactically valid function declaration | |
s = s // "function name (a, b, c) { body }" | |
.substring( // "a, b, c" | |
s.indexOf('(')+1, // ----------------^ | |
s.indexOf(')') // ------^ | |
); | |
// Cleanup the string, ignore spaces and linefeeds, only identifiers matter | |
s = s.replace(/[\r\n\s]*/g, ''); // "a,b,c" | |
// Let's be ES6-ready: any argument can be followed by '= default value' | |
s = s // a,b="\"toto\"",c='hello',d=3342,e,f | |
.replace(/\\+['"]/g, '') // a,b="toto",c='hello',d=3342,e,f | |
.replace(/=\s*(["']).*?\1/g, '') // a,b,c,d=3342,e,f | |
.replace(/=.*?(,|$)/g, '') // a,b,c,d,e,f | |
return s.split(','); // ["a", "b", "c"] | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this can be tricked by putting comments in argnames