Skip to content

Commit b964b3d

Browse files
committed
Utility for stripping comments.
1 parent b4c3e57 commit b964b3d

File tree

3 files changed

+29
-0
lines changed

3 files changed

+29
-0
lines changed

src/__tests__/stripComments.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import ava from "ava";
2+
import stripComments from "../../src/util/stripComments";
3+
4+
ava("stripComments()", (t) => {
5+
t.deepEqual(stripComments("aaa/**/bbb"), "aaabbb");
6+
t.deepEqual(stripComments("aaa/*bbb"), "aaa");
7+
t.deepEqual(stripComments("aaa/*xxx*/bbb"), "aaabbb");
8+
t.deepEqual(stripComments("aaa/*/xxx/*/bbb"), "aaabbb");
9+
t.deepEqual(stripComments("aaa/*x*/bbb/**/"), "aaabbb");
10+
t.deepEqual(stripComments("/**/aaa/*x*/bbb/**/"), "aaabbb");
11+
t.deepEqual(stripComments("/**/"), "");
12+
});

src/util/index.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
export {default as unesc} from './unesc';
22
export {default as getProp} from './getProp';
33
export {default as ensureObject} from './ensureObject';
4+
export {default as stripComments} from './stripComments';

src/util/stripComments.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
export default function stripComments (str) {
2+
let s = "";
3+
let commentStart = str.indexOf("/*");
4+
let lastEnd = 0;
5+
while (commentStart >= 0) {
6+
s = s + str.slice(lastEnd, commentStart);
7+
let commentEnd = str.indexOf("*/", commentStart + 2);
8+
if (commentEnd < 0) {
9+
return s;
10+
}
11+
lastEnd = commentEnd + 2;
12+
commentStart = str.indexOf("/*", lastEnd);
13+
}
14+
s = s + str.slice(lastEnd);
15+
return s;
16+
}

0 commit comments

Comments
 (0)