• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1'use strict';
2var singleComment = 1;
3var multiComment = 2;
4
5function stripWithoutWhitespace() {
6	return '';
7}
8
9function stripWithWhitespace(str, start, end) {
10	return str.slice(start, end).replace(/\S/g, ' ');
11}
12
13module.exports = function (str, opts) {
14	opts = opts || {};
15
16	var currentChar;
17	var nextChar;
18	var insideString = false;
19	var insideComment = false;
20	var offset = 0;
21	var ret = '';
22	var strip = opts.whitespace === false ? stripWithoutWhitespace : stripWithWhitespace;
23
24	for (var i = 0; i < str.length; i++) {
25		currentChar = str[i];
26		nextChar = str[i + 1];
27
28		if (!insideComment && currentChar === '"') {
29			var escaped = str[i - 1] === '\\' && str[i - 2] !== '\\';
30			if (!escaped) {
31				insideString = !insideString;
32			}
33		}
34
35		if (insideString) {
36			continue;
37		}
38
39		if (!insideComment && currentChar + nextChar === '//') {
40			ret += str.slice(offset, i);
41			offset = i;
42			insideComment = singleComment;
43			i++;
44		} else if (insideComment === singleComment && currentChar + nextChar === '\r\n') {
45			i++;
46			insideComment = false;
47			ret += strip(str, offset, i);
48			offset = i;
49			continue;
50		} else if (insideComment === singleComment && currentChar === '\n') {
51			insideComment = false;
52			ret += strip(str, offset, i);
53			offset = i;
54		} else if (!insideComment && currentChar + nextChar === '/*') {
55			ret += str.slice(offset, i);
56			offset = i;
57			insideComment = multiComment;
58			i++;
59			continue;
60		} else if (insideComment === multiComment && currentChar + nextChar === '*/') {
61			i++;
62			insideComment = false;
63			ret += strip(str, offset, i + 1);
64			offset = i + 1;
65			continue;
66		}
67	}
68
69	return ret + (insideComment ? strip(str.substr(offset)) : str.substr(offset));
70};
71