Permalink
Browse files

feat: get function parameter names

  • Loading branch information...
XadillaX committed Aug 9, 2016
1 parent c2e83cf commit 7240c0b15836afe096185d359808821debc00a3e
Showing with 65 additions and 1 deletion.
  1. +2 −1 package.json
  2. +37 −0 test/common.js
  3. +26 −0 util/common.js
@@ -24,6 +24,7 @@
"mocha": "3.0.1",
"mysql": "^2.11.1",
"mysql2": "^1.0.0-rc.9",
"otrans": "^1.0.0",
"should": "10.0.0",
"sync-runner": "^0.1.5",
"validate-commit-msg": "2.6.1"
@@ -67,4 +68,4 @@
"pre-push": "npm test"
}
}
}
}
@@ -0,0 +1,37 @@
/**
* XadillaX created at 2016-08-09 10:32:04 With ♥
*
* Copyright (c) 2016 Souche.com, all rights
* reserved.
*/
"use strict";

require("should");

const common = require("../util/common");

describe("🐣 common", function() {
describe("👙 getParamNames", function() {
it("should recognize no argument", function() {
let func;
func = (function() {});
common.getParamNames(func).should.deepEqual([]);
func = (function() { return function() {}; })();
common.getParamNames(func).should.deepEqual([]);
func = function() { console.log("function(argu) {}"); };
common.getParamNames(func).should.deepEqual([]);
eval("func = function ( \n \n \n \t) { }"); // jshint ignore: line
common.getParamNames(func).should.deepEqual([]);
});

it("should recognize arguments", function() {
let func;
func = function(foo, bar) {}; // jshint ignore: line
common.getParamNames(func).should.deepEqual([ "foo", "bar" ]);
func = (function(_asdf, 囍, _, λ) {}) ;// jshint ignore: line
common.getParamNames(func).should.deepEqual([ "_asdf", "", "_", "λ" ]);
eval("func = function ( as \n , sadf, /** sadf, */ 我, _ \n \n \t) { //\n this.a = 1; }"); // jshint ignore: line
common.getParamNames(func).should.deepEqual([ "as", "sadf", "", "_" ]);
});
});
});
@@ -0,0 +1,26 @@
/**
* XadillaX created at 2016-08-09 10:17:01 With ♥
*
* Copyright (c) 2016 Souche.com, all rights
* reserved.
*/
"use strict";

const debug = require("debug")("toshihiko:common");

const STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
const ARGUMENT_NAMES = /([^\s,]+)/g;

const common = module.exports = {};

/**
* get param names for a function
* @param {Function} func the function which will be parsed
* @returns {Array} the param names
*/
common.getParamNames = function(func) {
const fnStr = func.toString().replace(STRIP_COMMENTS, "");
debug("function detected.", fnStr);
const result = fnStr.slice(fnStr.indexOf("(") + 1, fnStr.indexOf(")")).match(ARGUMENT_NAMES);
return (null === result) ? [] : result;
};

0 comments on commit 7240c0b

Please sign in to comment.