diff --git a/lib/function.js b/lib/function.js new file mode 100644 index 0000000..bb8a2ad --- /dev/null +++ b/lib/function.js @@ -0,0 +1,22 @@ +module.exports = (function ( Util ){ + var fn = Util.function = {}, + + // REGEX + STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg, + ARGUMENT_NAMES = /([^\s,]+)/g; + + // Based on @Jack Allan's response at stackoverflow.com + // http://stackoverflow.com/questions/1007981/how-to-get-function-parameter-names-values-dynamically-from-javascript + fn.getParamNames = function ( func ) { + + var fnStr = func.toString().replace(STRIP_COMMENTS, ''); + var result = fnStr.slice(fnStr.indexOf('(')+1, fnStr.indexOf(')')).match(ARGUMENT_NAMES); + + if(result === null) { + result = []; + } + + return result; + }; + +}); \ No newline at end of file diff --git a/lib/util.js b/lib/util.js index e78df26..6bc09b8 100644 --- a/lib/util.js +++ b/lib/util.js @@ -14,6 +14,7 @@ module.exports = (function () { var Util = {}; require('./core')( Util ); + require('./function')( Util ); require('./is-isnt')( Util ); require('./from')( Util ); require('./to')( Util ); diff --git a/tests/function.test.js b/tests/function.test.js new file mode 100644 index 0000000..56dfdb3 --- /dev/null +++ b/tests/function.test.js @@ -0,0 +1,37 @@ +var Util = require('../index'), + + sinon = require('sinon'), + chai = require('chai'), + expect = chai.expect; + +describe( "Util", function () { + + describe( ".function", function () { + + describe( ".getParamNames", function () { + + it( "no parameters provided", function (){ + + var res = Util.function.getParamNames( function ( ) {} ); + + expect( Util.is.Array( res ) ).to.be.ok; + expect( res ).to.have.length( 0 ); + + }); + + it( "'a' and 'b' parameters provided", function (){ + + var res = Util.function.getParamNames( function ( a, b ) {} ); + + expect( Util.is.Array( res ) ).to.be.ok; + expect( res ).to.have.length( 2 ); + expect( res[0] ).to.be.equal( 'a' ); + expect( res[1] ).to.be.equal( 'b' ); + + }); + + }); + + }); + +}); \ No newline at end of file