4 ms·
I’ve found generator functions work great for parsers. You yield the tokens you expect to be next. The token could be a string, a regular expression to be match
by burntcaramel 5y ago
I’ve found generator functions work great for parsers. You yield the tokens you expect to be next. The token could be a string, a regular expression to be matched, or another generator function.
The library is open source here, contributions welcome: https://github.com/RoyalIcing/yieldparser https://github.com/RoyalIcing/yieldparser
Generator functions have great support in modern browsers (not IE) and Node.js.
For example here’s a simple v4 IP address parser:
import { parse, mustEnd } from 'yieldparser';
function* Digit() {
const [digit]: [string] = yield /^\d+/;
const value = parseInt(digit, 10);
if (value < 0 || value > 255) {
return new Error(`Digit must be between 0 and 255, was ${value}`);
}
return value;
}
function* IPAddress() {
const first = yield Digit;
yield '.';
const second = yield Digit;
yield '.';
const third = yield Digit;
yield '.';
const fourth = yield Digit;
yield mustEnd;
return [first, second, third, fourth];
}
parse('1.2.3.4', IPAddress());
/*
{
success: true,
result: [1, 2, 3, 4],
remaining: '',
}
*/