Last active
October 13, 2015 20:47
Gets the function argument names in an Array
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 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"] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment