michaelp0730
1/19/2015 - 6:29 PM

John Resig - Argument names

function argumentNames(fn) {
	var found = /^[\s\(]*function[^(]*\(\s*([^)]*?)\s*\)/.exec(fn.toString());
	return found && found[1] ? found[1].split(/,\s*/) : [];
}

// use custom assert method for testing
assert(argumentNames(function () {}).length === 0, "Works on zero-arg functions.");

assert(argumentNames(function (x) {})[0] === "x", "Single argument working");

var results = argumentNames(function(a,b,c,d,e) {});
assert( results[0] === 'a' &&
		results[1] === 'b' &&
		results[2] === 'c' &&
		results[3] === 'd' &&
		results[4] === 'e',
		"Multiple arguments working");