Skip to content

Commit

Permalink
Correct regex for function source cleaning
Browse files Browse the repository at this point in the history
- Treat tabs etc. as spaces.
- Match function name for removal.
- Match only non-`)` inside the function parameter list for removal instead of `.`; prevents matching through later in the first line e.g. `function(){ if ([condition]) { ...`.
- Match 0 or more spaces before } on the end for removal rather than 1 or more.
- Make the closing } optional for arrow functions with a single-statement body just like the opening {.
- Add tests for these cases.
  • Loading branch information
ScottFreeCode committed Jun 1, 2016
1 parent e939d8e commit 6d60200
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
4 changes: 2 additions & 2 deletions lib/utils.js
Expand Up @@ -264,8 +264,8 @@ exports.slug = function(str) {
exports.clean = function(str) {
str = str
.replace(/\r\n?|[\n\u2028\u2029]/g, '\n').replace(/^\uFEFF/, '')
.replace(/^function *\(.*\)\s*\{|\(.*\) *=> *\{?/, '')
.replace(/\s+\}$/, '');
// (traditional)-> space/name parameters body (lambda)-> parameters body multi-statement/single keep body content
.replace(/^function(?:\s*|\s+[^(]*)\([^)]*\)\s*\{((?:.|\n)*?)\s*\}$|^\([^)]*\)\s*=>\s*(?:\{((?:.|\n)*?)\s*\}|((?:.|\n)*))$/, '$1$2$3');

var spaces = str.match(/^\n?( *)/)[1].length;
var tabs = str.match(/^\n?(\t*)/)[1].length;
Expand Down
24 changes: 24 additions & 0 deletions test/utils.js
Expand Up @@ -19,6 +19,30 @@ describe('utils', function() {
it('should remove tab character indentation from the function body', function() {
clean('\t//line1\n\t\t//line2').should.equal('//line1\n\t//line2');
});

it('should handle functions with tabs in their declarations', function() {
clean('function\t(\t)\t{\n//code\n}').should.equal('//code');
});

it('should handle named functions without space after name', function() {
clean('function withName() {\n//code\n}').should.equal('//code');
});

it('should handle named functions with space after name', function() {
clean('function withName () {\n//code\n}').should.equal('//code');
});

it('should handle functions with no space between the end and the closing brace', function() {
clean('function() {/*code*/}').should.equal('/*code*/');
});

it('should handle functions with parentheses in the same line', function() {
clean('function() { if (true) { /* code */ } }').should.equal('if (true) { /* code */ }');
});

it('should handle empty functions', function() {
clean('function() {}').should.equal('');
});
});

describe('.isBuffer()', function() {
Expand Down

0 comments on commit 6d60200

Please sign in to comment.