-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathindex.js
113 lines (94 loc) · 1.94 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
111
112
113
module.exports = parse;
function parse(str) {
return new Parser(str).parse();
}
function Parser(str) {
this.str = str;
}
Parser.prototype.skip = function(m){
this.str = this.str.slice(m[0].length);
};
Parser.prototype.comma = function(){
var m = /^, */.exec(this.str);
if (!m) return;
this.skip(m);
return { type: 'comma', string: ',' };
};
Parser.prototype.ident = function(){
var m = /^([\w-]+) */.exec(this.str);
if (!m) return;
this.skip(m);
return {
type: 'ident',
string: m[1]
}
};
Parser.prototype.int = function(){
var m = /^((\d+)(\S+)?) */.exec(this.str);
if (!m) return;
this.skip(m);
var n = ~~m[2];
var u = m[3];
return {
type: 'number',
string: m[1],
unit: u || '',
value: n
}
};
Parser.prototype.float = function(){
var m = /^(((?:\d+)?\.\d+)(\S+)?) */.exec(this.str);
if (!m) return;
this.skip(m);
var n = parseFloat(m[2]);
var u = m[3];
return {
type: 'number',
string: m[1],
unit: u || '',
value: n
}
};
Parser.prototype.number = function(){
return this.float() || this.int();
};
Parser.prototype.double = function(){
var m = /^"([^"]*)" */.exec(this.str);
if (!m) return m;
this.skip(m);
return {
type: 'string',
quote: '"',
string: '"' + m[1] + '"',
value: m[1]
}
};
Parser.prototype.single = function(){
var m = /^'([^']*)' */.exec(this.str);
if (!m) return m;
this.skip(m);
return {
type: 'string',
quote: "'",
string: "'" + m[1] + "'",
value: m[1]
}
};
Parser.prototype.string = function(){
return this.single() || this.double();
};
Parser.prototype.value = function(){
return this.number()
|| this.ident()
|| this.string()
|| this.comma();
};
Parser.prototype.parse = function(){
var vals = [];
while (this.str.length) {
var obj = this.value();
if (!obj) throw new Error('failed to parse near `' + this.str.slice(0, 10) + '...`');
vals.push(obj);
}
return vals;
};