From 6d602003bbc36a9d964443cca8030360e619664c Mon Sep 17 00:00:00 2001 From: ScottFreeCode Date: Fri, 15 Apr 2016 00:44:08 -0400 Subject: [PATCH] Correct regex for function source cleaning - 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. --- lib/utils.js | 4 ++-- test/utils.js | 24 ++++++++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/lib/utils.js b/lib/utils.js index e5d214021c..35e59c09c5 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -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; diff --git a/test/utils.js b/test/utils.js index 6cebc5ab68..881e5342a9 100644 --- a/test/utils.js +++ b/test/utils.js @@ -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() {