Skip to content

Commit

Permalink
perf(parse): major speedup satisfy() (~1.6x faster)
Browse files Browse the repository at this point in the history
- update ParseContext.addChild() to optionally progress reader
- update call sites in satisfy(), lift(), repeat()
  • Loading branch information
postspectacular committed Apr 16, 2020
1 parent 05bef98 commit 8ca5c7f
Show file tree
Hide file tree
Showing 4 changed files with 9 additions and 13 deletions.
2 changes: 1 addition & 1 deletion packages/parse/src/combinators/repeat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export const repeat = <T>(
id = "repeat"
): Parser<T> => (ctx) => {
if (ctx.done) {
return min < 1 ? (ctx.addChild(id), true) : false;
return min < 1 ? ctx.addChild(id) : false;
}
ctx.start(id);
for (let i = 0; i < max; i++) {
Expand Down
7 changes: 5 additions & 2 deletions packages/parse/src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ export class ParseContext<T> {
return true;
}

addChild(id: string, result: any = null) {
addChild(id: string, result: any = null, consume = false) {
const curr = this._curr;
const cstate = curr.state;
const child: ParseScope<T> = {
Expand All @@ -116,7 +116,10 @@ export class ParseContext<T> {
};
const children = curr.children;
children ? children.push(child) : (curr.children = [child]);
return child;
if (consume) {
this.reader.next(cstate!);
}
return true;
}

get scope() {
Expand Down
5 changes: 1 addition & 4 deletions packages/parse/src/prims/lift.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,4 @@ import type { Lift, Parser } from "../api";

export const lift = <R = any>(result: Lift<R>, id = "lift"): Parser<any> => (
ctx
) => {
ctx.addChild(id, isFunction(result) ? result() : result);
return true;
};
) => ctx.addChild(id, isFunction(result) ? result() : result);
8 changes: 2 additions & 6 deletions packages/parse/src/prims/satisfy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,9 @@ export const satisfy = <T>(fn: Predicate<T>, id = "lit"): Parser<T> => (
ctx
) => {
if (ctx.done) return false;
const reader = ctx.reader;
const r = reader.read(ctx.state!);
const r = ctx.reader.read(ctx.state!);
if (!fn(r)) {
return false;
}
const scope = ctx.start(id);
reader.next(scope.state!);
scope.result = r;
return ctx.end();
return ctx.addChild(id, r, true);
};

0 comments on commit 8ca5c7f

Please sign in to comment.