@thi.ng/parse
Version:
Purely functional parser combinators & AST generation for generic inputs
30 lines (29 loc) • 846 B
JavaScript
import { discard } from "../xform/discard.js";
const repeat = (parser, min, max, id = "repeat") => (ctx) => {
if (ctx.done) {
return min < 1 ? ctx.addChild(id) : false;
}
ctx.start(id);
for (let i = 0; i < max; i++) {
if (!parser(ctx)) {
if (i < min) {
return ctx.discard();
}
break;
}
}
return ctx.end();
};
const zeroOrMore = (parser, id = "repeat0", max = Infinity) => repeat(parser, 0, max, id);
const oneOrMore = (parser, id = "repeat1", max = Infinity) => repeat(parser, 1, max, id);
const repeatD = (parser, min, max) => discard(repeat(parser, min, max));
const zeroOrMoreD = (parser, max = Infinity) => repeatD(parser, 0, max);
const oneOrMoreD = (parser, max = Infinity) => repeatD(parser, 1, max);
export {
oneOrMore,
oneOrMoreD,
repeat,
repeatD,
zeroOrMore,
zeroOrMoreD
};