File tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed
Filter options
Expand file tree Collapse file tree 1 file changed +54
-0
lines changed
Original file line number Diff line number Diff line change
1
+ 'use strict' ;
2
+
3
+ class LiteralParser {
4
+ constructor ( meta ) {
5
+ this . state = 'start' ;
6
+ this . meta = meta ;
7
+ }
8
+
9
+ feed ( char ) {
10
+ const cases = this . meta [ this . state ] ;
11
+ for ( const [ key , to ] of Object . entries ( cases ) ) {
12
+ if ( key . includes ( char ) ) {
13
+ if ( typeof to === 'string' ) throw Error ( to ) ;
14
+ to ( this , char ) ;
15
+ return ;
16
+ }
17
+ if ( key === '' ) throw Error ( to ) ;
18
+ }
19
+ }
20
+
21
+ parse ( string ) {
22
+ for ( const char of string ) this . feed ( char ) ;
23
+ return this . result ;
24
+ }
25
+ }
26
+
27
+ // Usage
28
+
29
+ const parser = new LiteralParser ( {
30
+ start : {
31
+ '[' : ( target ) => {
32
+ target . result = [ ] ;
33
+ target . value = '' ;
34
+ target . state = 'value' ;
35
+ } ,
36
+ '' : 'Unexpected character before array' ,
37
+ } ,
38
+ value : {
39
+ ' .-0123456789' : ( target , char ) => target . value += char ,
40
+ ',]' : ( target , char ) => {
41
+ const value = parseFloat ( target . value ) ;
42
+ target . result . push ( value ) ;
43
+ target . value = '' ;
44
+ if ( char === ']' ) target . state = 'end' ;
45
+ } ,
46
+ '' : 'Unexpected character in value' ,
47
+ } ,
48
+ end : {
49
+ '' : 'Unexpected character after array' ,
50
+ } ,
51
+ } ) ;
52
+
53
+ const array = parser . parse ( '[5, 7.1, -2, 194.5, 32]' ) ;
54
+ console . log ( { array } ) ;
You can’t perform that action at this time.
0 commit comments