-
Notifications
You must be signed in to change notification settings - Fork 2
/
ParsePath.js
97 lines (93 loc) · 2.38 KB
/
ParsePath.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
module.exports = function(path) {
if (!path) return [];
if (typeof path !== 'string') return [];
// return path
// .replace(/\[|\]/g, '.')
// .replace(/\.+/g, '.')
// .replace(/^\.|\.$/g, '')
// .split('.')
// .map(function (value) {
// return value.replace(/^["']|["']$/g, '');
// });
var number = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9};
var currentProperty = null;
var isNumber = false;
var stack = [];
var result = [];
for (var i = 0; i < path.length; i++) {
var char = path[i];
if (stack.length > 0) {
var last = stack[stack.length - 1];
if (last === "[" && char === "]") {
stack.pop();
}
else if (last !== "[" && last === char) {
stack.pop();
}
else if (last !== "'" && last !== '"' && (char === "'" || char == '"')) {
stack.push(char);
isNumber = false;
}
else if (last !== "'" && last !== '"' && char === '[') {
stack.push(char);
}
else {
currentProperty = (currentProperty || '') + char;
}
}
else {
if (char === '.') {
if (currentProperty !== null) {
if (isNumber) {
var number = parseInt(currentProperty);
if (Number.isNaN(number)) {
throw new Error('Can not parse this path: ' + path + '. Check property: ' + currentProperty);
}
else {
result.push(number);
}
}
else {
result.push(currentProperty);
}
}
currentProperty = null;
isNumber = false;
}
else if (char == '[') {
if (currentProperty !== null) {
if (isNumber) {
var number = parseInt(currentProperty);
if (Number.isNaN(number)) {
throw new Error('Can not parse this path: ' + path + '. Check property: ' + currentProperty);
}
else {
result.push(number);
}
}
else {
result.push(currentProperty);
}
}
currentProperty = null;
isNumber = true;
stack.push(char);
}
else if (!currentProperty && (char === "'" || char == '"')) {
stack.push(char);
isNumber = false;
}
else if (char === ']') {
throw new Error('Can not parse this path: ' + path + '. Check symbol: ]');
}
else {
currentProperty = (currentProperty || '') + char;
}
}
}
currentProperty && result.push(currentProperty);
if (stack.length > 0) {
throw new Error('Can not parse this path: ' + path + '. Check symbol: ' + stack);
}
return result;
}