-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
110 lines (87 loc) · 2.16 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
"use strict";
module.exports = function(input) {
if (typeof input !== 'string') {
throw new Error('Invalid input type');
}
var reading = false;
var startChar = null;
var startIndex = null;
var read = function(s, e) {
reading = false;
startChar = null;
startIndex = null;
return input.substring(s, e);
}
var result = Array.prototype.reduce.call(
input.trim(),
function(result, value, index, arr) {
if (reading && startChar === ' ' && special(value) && !isWhitespace(value)) {
throw new Error("Invalid argument(s)");
}
if (! (reading || special(value))) {
reading = true;
startChar = ' ';
startIndex = index;
if (index === arr.length - 1 && startChar === ' ') {
return result.concat([
read(startIndex)
]);
}
return result;
}
if (!reading && special(value) && !isWhitespace(value)) {
reading = true;
startChar = value;
startIndex = index;
return result;
}
if (!reading) {
return result;
}
if (startChar === ' ' && isWhitespace(value)) {
if (!isValid(index, arr)) {
throw new Error("Invalid syntax");
}
return result.concat([read(startIndex, index)]);
}
if (startChar === value && special(startChar) && isValid(index, arr)) {
return result.concat([
read(startIndex + 1, index)
]);
}
if (index === arr.length - 1 && startChar === ' ') {
return result.concat([
read(startIndex)
]);
}
return result;
},
[]
);
if (startIndex || startChar) {
throw new Error('Unexpected end of input');
}
return result.map(function(str) {
return str.replace(/\\([\s"'\\])/g, '$1');
});
}
function isWhitespace(c) {
return /\s/.test(c);
};
function special(c) {
return /\s|"|'/.test(c);
};
function isValid(index, arr) {
var counter = 0;
while (true) {
if (index - 1 - counter < 0) {
break;
}
if (arr[index - 1 - counter] === '\\') {
counter++;
continue;
}
break;
}
return counter % 2 === 0;
}