Skip to content

Commit 5eb639d

Browse files
committed
Extract remove comments into a function
1 parent e1e02f9 commit 5eb639d

File tree

3 files changed

+56
-3
lines changed

3 files changed

+56
-3
lines changed

src/index.js

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
const generate = require('babel-generator').default;
22

33
const looksLike = require('./utils/looks-like');
4+
const { removeComments } = require('./utils');
45

56
module.exports = function({ template, types }) {
67
return {
@@ -51,9 +52,7 @@ module.exports = function({ template, types }) {
5152

5253
// generate the code
5354
const { code } = generate(body);
54-
55-
// remove comments
56-
const normalisedCode = code.replace(/\/\/(.*)/g, '').replace(/\/\*([\s\S]*?)\*\//g, '');
55+
const normalisedCode = removeComments(code);
5756

5857
const count = (normalisedCode.match(/expect\(/g) || []).length;
5958
const containsExpectAssertions = normalisedCode.includes('expect.assertions(');

src/utils/index.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
const EMPTY = '';
2+
const SINGLE_LINE_COMMENT = /\/\/(.*)/g;
3+
const MULTI_LINE_COMMENT = /\/\*([\s\S]*?)\*\//g;
4+
5+
const removeComments = code => code.replace(SINGLE_LINE_COMMENT, EMPTY).replace(MULTI_LINE_COMMENT, EMPTY);
6+
7+
module.exports = {
8+
removeComments
9+
};

src/utils/index.test.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
const { removeComments } = require('./');
2+
3+
describe('Utils', () => {
4+
describe('.removeComments', () => {
5+
it('returns given string when string does not contain any comments', () => {
6+
const str = 'hello world';
7+
expect(removeComments(str)).toEqual(str);
8+
});
9+
it('returns empty string when given a single line comment', () => {
10+
expect(removeComments('// hello world')).toEqual('');
11+
});
12+
it('returns empty string when given a multi line comment', () => {
13+
expect(
14+
removeComments(`/*
15+
hello world
16+
*/`)
17+
).toEqual('');
18+
});
19+
it('returns string without comments when given a string containing a singleline comment', () => {
20+
expect(removeComments('abc//hello world')).toEqual('abc');
21+
});
22+
it('returns string without comments when given a string containing a multi line comment', () => {
23+
expect(
24+
removeComments(`abc/*
25+
hello world
26+
*/def`)
27+
).toEqual('abcdef');
28+
});
29+
it('returns string without comments when given a string with both single and multi line comments', () => {
30+
expect(
31+
removeComments(`abc /* hello world */
32+
// foo
33+
/*
34+
bar
35+
*/
36+
xyz
37+
/*
38+
baz
39+
*/
40+
def // qux
41+
`).replace(/\s/g, '')
42+
).toEqual('abcxyzdef');
43+
});
44+
});
45+
});

0 commit comments

Comments
 (0)