Skip to content

armgit / mocha

Public Imported from GitHub
0

☕️ Classic, reliable, trusted test framework for Node.js and the browser

Correct regex for function source cleaning

ScottFreeCode6d602003bbc3
diff --git a/lib/utils.js b/lib/utils.js
index e5d21402..35e59c09 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 6cebc5ab..881e5342 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() {