Skip to content
This repository has been archived by the owner on Dec 29, 2022. It is now read-only.

Commit

Permalink
Merge pull request #5 from pguillory/stringify-function
Browse files Browse the repository at this point in the history
Normalize whitespace around function arguments
  • Loading branch information
jacobsa committed May 20, 2015
2 parents 022daf6 + c45acee commit 8cc4dab
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 10 deletions.
24 changes: 15 additions & 9 deletions gjstest/public/stringify.js
Expand Up @@ -82,16 +82,22 @@ gjstest.internal.stringifyToDepth = function(obj, depth) {
return '\'' + obj.replace(/\n/g, '\\n') + '\'';
}

// Special-case: functions should have their names (if any) printed:
// function: fooBar
// function: (anonymous)
// Special-case: functions should have their names and arguments (if any)
// printed, but leave off the bodies:
// function fooBar() (named function)
// function () (anonymous function)
//
// Function.prototype.toString returns things like:
// function fooBar(asd) { return 17; }
// function (asd) {}
var match;
if (match = /^(function (\S+)?\([^()]*\)) {[\s\S]*}$/.exec(naiveResult)) {
return match[1];
// Function.prototype.toString returns the exact source of the function, from
// the 'f' in 'function' to the closing brace of the function body. We'll need
// to account for potential whitespace around the function name and arguments.
// function fooBar(foo, bar) { return 17; }
// function() {}
var functionRegex = /^function(\s+(\w+))?\s*\(\s*(\w+(\s*,\s*\w+)*)?\s*\)/;
var match, functionName, functionArgs;
if (match = functionRegex.exec(naiveResult)) {
functionName = match[2] || '';
functionArgs = (match[3] || '').replace(/\s*,\s*/g, ', ');
return 'function ' + functionName + '(' + functionArgs + ')';
}

return '' + obj;
Expand Down
2 changes: 1 addition & 1 deletion gjstest/public/stringify_test.js
Expand Up @@ -58,7 +58,7 @@ StringifyTest.prototype.Functions = function() {

expectEq('function fooBar(baz)', stringify(fooBar));
expectEq('function ()', stringify(function() {}));
expectEq('function (foo, bar)', stringify(function(foo, bar) {}));
expectEq('function (foo, bar)', stringify(function( foo , bar ) {}));
};

StringifyTest.prototype.Objects = function() {
Expand Down

0 comments on commit 8cc4dab

Please sign in to comment.