-
Notifications
You must be signed in to change notification settings - Fork 0
/
strip-comments.js
45 lines (32 loc) · 1.34 KB
/
strip-comments.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
* http://www.codewars.com/kata/51c8e37cee245da6b40000bd/
*
Description:
Complete the solution so that it strips all text that follows any of a set of comment markers passed in. Any whitespace at the end of the line should also be stripped out.
Example:
Given an input string of:
apples, pears # and bananas
grapes
bananas !apples
The output expected would be:
apples, pears
grapes
bananas
The code would be called like so:
var result = solution("apples, pears # and bananas\ngrapes\nbananas !apples", ["#", "!"])
// result should == "apples, pears\ngrapes\nbananas"
*
*/
let tests = require('./lib/framework.js');
let Test = tests.Test, describe = tests.describe, it = tests.it, before = tests.before, after = tests.after;
function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
function solution(input, markers) {
let reg = new RegExp('(\s*)(' + markers.map(escapeRegExp).join('|') + ').*$', 'g');
return input.split("\n").map(function (line) {
return line.replace(reg, '').replace(/(\s*)$/, '');
}).join("\n");
}
Test.assertEquals(solution("apples, pears # and bananas\ngrapes\nbananas !apples", ["#", "!"]), "apples, pears\ngrapes\nbananas", 0);
Test.assertEquals(solution("a #b\nc\nd $e f g", ['#', '$']), "a\nc\nd", 0);