public
Last active

Gets the function argument names in an Array

  • Download Gist
functionRegExp.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
function injector (objects) {
function functionArgsName(fn) {
var fragment;
fn = fn.toString();
//remove comments
fn = fn.replace(/(\/\*([\s\S]*?)\*\/)|(\/\/(.*)$)/gm,"");
fragment = fn.match(/function\s*\w*\s*\((.*?)\)/)[1];
if (!/^[\s]*$/g.test(fragment)) {
return fragment.replace(/(\s)/g,"").split(",");
} else return [];
}
return {
inject : function (fn) {
var args, i = 0, toInject;
args = functionArgsName(fn);
i = args.length;
while(i--) {
if (objects[args[i]]) {
toInject.push(objects[args[i]]);
}
}
fn.apply(fn, toInject);
}
}
}
 
function functionArgsName(fn) {
var fragment;
fn = fn.toString();
//remove comments
fn = fn.replace(/(\/\*([\s\S]*?)\*\/)|(\/\/(.*)$)/gm,"");
fragment = fn.match(/function\s*\w*\s*\((.*?)\)/)[1];
if (!/^[\s]*$/g.test(fragment)) {
return fragment.replace(/(\s)/g,"").split(",");
} else return [];
}
// Tests
console.log(functionArgsName(function(){}));
console.log(functionArgsName(function( ){}));
console.log(functionArgsName(function( param1 ){}));
console.log(functionArgsName(function( param1 , $param2 ){}));
console.log(functionArgsName(function(param1, $param2){}));
console.log(functionArgsName(function( $param1){}));
console.log(functionArgsName(function(param1,$param2){}));
console.log(functionArgsName(function(param1,/*comment here*/ $param2asdads){}));
console.log(functionArgsName(function(/**/param1,/*(function(name,name))*/ $param2asdads){}));
console.log(functionArgsName(function /* you can do this */ (param1, $param2asdads){}));
/* OUTPUT
[]
[]
["param1"]
["param1", "$param2"]
["param1", "$param2"]
["$param1"]
["param1", "$param2"]
["param1", "$param2asdads"]
["param1", "$param2asdads"]
["param1", "$param2asdads"]
*/

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.