Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit b73ebd5

Browse filesBrowse files
committed
Add declarative implementation
1 parent 568ec59 commit b73ebd5
Copy full SHA for b73ebd5

File tree

Expand file treeCollapse file tree

1 file changed

+54
-0
lines changed
Filter options
Expand file treeCollapse file tree

1 file changed

+54
-0
lines changed

‎JavaScript/5-declarative.js

Copy file name to clipboard
+54Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
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 });

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.