-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpathParser.js
68 lines (56 loc) · 1.31 KB
/
pathParser.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
import { isString } from '../../lang/is/is'
const PATH_Token = {
Identifier: 1,
ACC: 2,
ARR_START: 3,
ARR_END: 4
}
function toToken(char) {
if (char === '.') return PATH_Token.ACC
if (char === '[') return PATH_Token.ARR_START
if (char === ']') return PATH_Token.ARR_END
return PATH_Token.Identifier
}
export const pathParser = str => {
if (!isString(str) || !str.length) {
return []
}
const res = []
const length = str.length
let index = 0
let token
let curr
let identifier = ''
while (index < length) {
curr = str[index]
token = toToken(curr)
if (token === PATH_Token.ACC) {
// keep identifier
if (identifier.length) {
res.push(identifier)
identifier = ''
}
} else if (token === PATH_Token.ARR_START) {
// ignore '[' and save identifier
if (identifier.length) {
res.push(identifier)
identifier = ''
}
} else if (token === PATH_Token.ARR_END) {
// ignore ']' and save array index number
const arrIndex = parseInt(identifier, 10)
identifier = ''
if (isFinite(arrIndex)) {
res.push(arrIndex)
}
} else {
identifier += curr
}
index += 1
// ending
if (index >= length && identifier.length) {
res.push(identifier)
}
}
return res
}