-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
66 lines (61 loc) · 1.83 KB
/
index.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
module.exports = str => {
const res = [];
if(!str || typeof str !== 'string') return res;
let sQuoted = false;
let dQuoted = false;
let backSlash = false;
let notEmpty = false;
let buffer = '';
str.split('').forEach((v, i, s) => {
if(sQuoted && v === `'`){
sQuoted = false;
notEmpty = true;
return;
}
if(!sQuoted && !dQuoted && !backSlash){
if(v === `'`){
sQuoted = true;
return;
}
if(v === '"'){
dQuoted = true;
return;
}
if(v === '\\'){
backSlash = true;
return;
}
if(['\b', '\f', '\n', '\r', '\t', ' '].includes(v)){
if(buffer.length > 0 || notEmpty){
res.push(buffer);
notEmpty = false;
}
buffer = '';
return;
}
}
if(!sQuoted && dQuoted && !backSlash && v === '"'){
dQuoted = false;
notEmpty = true;
return;
}
if(!sQuoted && dQuoted && !backSlash && v === '\\'){
backSlash = true;
if(['"', '`', '$', '\\'].includes(s[i + 1])){
return;
}
}
if(backSlash){
backSlash = false;
}
buffer += v;
});
if(buffer.length > 0 || notEmpty){
res.push(buffer);
notEmpty = false;
}
if(dQuoted) throw new SyntaxError('unexpected end of string while looking for matching double quote');
if(sQuoted) throw new SyntaxError('unexpected end of string while looking for matching single quote');
if(backSlash) throw new SyntaxError('unexpected end of string right after slash');
return res;
};