Blame view

node_modules/strip-json-comments/index.js 1.66 KB
ce4c83ff   wxy   初始提交
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
  'use strict';
  var singleComment = 1;
  var multiComment = 2;
  
  function stripWithoutWhitespace() {
  	return '';
  }
  
  function stripWithWhitespace(str, start, end) {
  	return str.slice(start, end).replace(/\S/g, ' ');
  }
  
  module.exports = function (str, opts) {
  	opts = opts || {};
  
  	var currentChar;
  	var nextChar;
  	var insideString = false;
  	var insideComment = false;
  	var offset = 0;
  	var ret = '';
  	var strip = opts.whitespace === false ? stripWithoutWhitespace : stripWithWhitespace;
  
  	for (var i = 0; i < str.length; i++) {
  		currentChar = str[i];
  		nextChar = str[i + 1];
  
  		if (!insideComment && currentChar === '"') {
  			var escaped = str[i - 1] === '\\' && str[i - 2] !== '\\';
  			if (!escaped) {
  				insideString = !insideString;
  			}
  		}
  
  		if (insideString) {
  			continue;
  		}
  
  		if (!insideComment && currentChar + nextChar === '//') {
  			ret += str.slice(offset, i);
  			offset = i;
  			insideComment = singleComment;
  			i++;
  		} else if (insideComment === singleComment && currentChar + nextChar === '\r\n') {
  			i++;
  			insideComment = false;
  			ret += strip(str, offset, i);
  			offset = i;
  			continue;
  		} else if (insideComment === singleComment && currentChar === '\n') {
  			insideComment = false;
  			ret += strip(str, offset, i);
  			offset = i;
  		} else if (!insideComment && currentChar + nextChar === '/*') {
  			ret += str.slice(offset, i);
  			offset = i;
  			insideComment = multiComment;
  			i++;
  			continue;
  		} else if (insideComment === multiComment && currentChar + nextChar === '*/') {
  			i++;
  			insideComment = false;
  			ret += strip(str, offset, i + 1);
  			offset = i + 1;
  			continue;
  		}
  	}
  
  	return ret + (insideComment ? strip(str.substr(offset)) : str.substr(offset));
  };