Skip to content

Commit 59dae34

Browse files
committed
add number parsing
1 parent 74da4a4 commit 59dae34

File tree

2 files changed

+41
-4
lines changed

2 files changed

+41
-4
lines changed

index.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,5 +2,42 @@
22
module.exports = parse;
33

44
function parse(str) {
5+
return new Parser(str).parse();
6+
}
57

8+
function Parser(str) {
9+
this.str = str;
610
}
11+
12+
Parser.prototype.skip = function(m){
13+
this.str = this.str.slice(m[0].length);
14+
};
15+
16+
Parser.prototype.number = function(){
17+
var m = /^(\d+)(\w+)? */.exec(this.str);
18+
if (!m) return;
19+
this.skip(m);
20+
var n = ~~m[1];
21+
var u = m[2];
22+
23+
return {
24+
type: 'number',
25+
string: n + u,
26+
unit: u,
27+
value: n
28+
}
29+
};
30+
31+
Parser.prototype.value = function(){
32+
return this.number();
33+
};
34+
35+
Parser.prototype.parse = function(){
36+
var vals = [];
37+
38+
while (this.str.length) {
39+
vals.push(this.value());
40+
}
41+
42+
return vals;
43+
};

test/cases/numbers.js

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@
22
exports.string = '1px 0 0 5px';
33

44
exports.object = [
5-
{ type: 'number', string: '1px', unit: 'px', number: 1 },
6-
{ type: 'number', string: '0', unit: '', number: 0 },
7-
{ type: 'number', string: '0', unit: '', number: 0 },
8-
{ type: 'number', string: '1px', unit: 'px', number: 5 },
5+
{ type: 'number', string: '1px', unit: 'px', value: 1 },
6+
{ type: 'number', string: '0', unit: '', value: 0 },
7+
{ type: 'number', string: '0', unit: '', value: 0 },
8+
{ type: 'number', string: '1px', unit: 'px', value: 5 },
99
];

0 commit comments

Comments
 (0)