Skip to content

Commit

Permalink
Add .function.getParamNames + tests
Browse files Browse the repository at this point in the history
  • Loading branch information
José Moreira committed Sep 1, 2014
1 parent 031bf70 commit b679782
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 0 deletions.
22 changes: 22 additions & 0 deletions lib/function.js
Original file line number Diff line number Diff line change
@@ -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;
};

});
1 change: 1 addition & 0 deletions lib/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 );
Expand Down
37 changes: 37 additions & 0 deletions tests/function.test.js
Original file line number Diff line number Diff line change
@@ -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' );

});

});

});

});

0 comments on commit b679782

Please sign in to comment.