@@ -73,7 +73,6 @@ function removeComments (source: string[]): string[] {
73
73
74
74
// 初始化状态
75
75
let charIndex = 0
76
- let isString = false
77
76
let resultString = ''
78
77
79
78
// 遍历代码字符
@@ -82,11 +81,24 @@ function removeComments (source: string[]): string[] {
82
81
const currentChar = sourceString [ charIndex ]
83
82
const nextChar = sourceString [ charIndex + 1 ]
84
83
85
- // 1. 设置字符串状态
86
- if ( currentChar === '"' ) isString = ! isString
84
+ // 1. 处理字符串
85
+ if ( currentChar === '"' ) {
86
+ // 寻找下一个“"”
87
+ const nextIndex = sourceString . indexOf ( '"' , charIndex )
88
+ // 找不到下一个“"”则说明直到代码结束都时该字符串也没有结束,将剩下的字符添加至 resultString,直接结束遍历
89
+ if ( nextIndex === - 1 ) {
90
+ resultString += sourceString . substring ( charIndex , sourceString . length )
91
+ break
92
+ }
93
+ // 将当前字符串代码添加至 resultString
94
+ resultString += sourceString . substring ( charIndex , nextIndex + 1 )
95
+ // 将字符索引设置为下一个“"”字符之后
96
+ charIndex = nextIndex + 1
97
+ continue
98
+ }
87
99
88
100
// 2. 跳过单行注释(不为字符串时,判断当前字符与下一个字符的组合是否为“//”)
89
- if ( ! isString && ( currentChar + nextChar === '//' ) ) {
101
+ if ( currentChar + nextChar === '//' ) {
90
102
// 寻找下一个换行符的位置
91
103
const nextIndex = sourceString . indexOf ( '\n' , charIndex )
92
104
// 找不到下一个换行符则说明直到代码结束都不在有换行符,直接结束遍历
@@ -97,7 +109,7 @@ function removeComments (source: string[]): string[] {
97
109
}
98
110
99
111
// 3. 跳过多行注释(不为字符串时,判断当前字符与下一个字符的组合是否为 “/*”)
100
- if ( ! isString && ( currentChar + nextChar === '/*' ) ) {
112
+ if ( currentChar + nextChar === '/*' ) {
101
113
// 将字符索引设置为下一个 “*/” 之后,开始查找的索引为当前 “/*” 之后
102
114
const nextIndex = sourceString . indexOf ( '*/' , charIndex + 2 )
103
115
if ( nextIndex === - 1 ) break
0 commit comments