Skip to content

Commit

Permalink
feat(parse): add count/xfCount transform
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Jun 27, 2020
1 parent 456efdc commit 056ae08
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 1 deletion.
5 changes: 4 additions & 1 deletion packages/parse/src/grammar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import { ESC, UNICODE } from "./presets/escape";
import { HEX_DIGIT } from "./presets/hex";
import { FLOAT, INT, UINT } from "./presets/numbers";
import { STRING } from "./presets/string";
import { WS, WS0, WS1 } from "./presets/whitespace";
import { NL, WS, WS0, WS1 } from "./presets/whitespace";
import { always } from "./prims/always";
import {
inputEnd,
Expand All @@ -37,6 +37,7 @@ import { oneOf } from "./prims/one-of";
import { range } from "./prims/range";
import { string, stringD } from "./prims/string";
import { collect, xfCollect } from "./xform/collect";
import { xfCount } from "./xform/count";
import { discard, xfDiscard } from "./xform/discard";
import { hoistResult, xfHoist, xfHoistResult } from "./xform/hoist";
import { join, xfJoin } from "./xform/join";
Expand Down Expand Up @@ -264,6 +265,7 @@ export const defGrammar = (
opts = { debug: false, optimize: true, ...opts };
env = {
collect: xfCollect,
count: xfCount,
discard: xfDiscard,
float: xfFloat,
hex: xfInt(16),
Expand Down Expand Up @@ -292,6 +294,7 @@ export const defGrammar = (
INT,
LEND: lineEnd,
LSTART: lineStart,
NL,
START: inputStart,
STRING,
UNICODE,
Expand Down
1 change: 1 addition & 0 deletions packages/parse/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ export * from "./readers/string-reader";

export * from "./xform/collect";
export * from "./xform/comp";
export * from "./xform/count";
export * from "./xform/discard";
export * from "./xform/hoist";
export * from "./xform/join";
Expand Down
21 changes: 21 additions & 0 deletions packages/parse/src/xform/count.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import type { Parser, ScopeTransform } from "../api";
import { xform } from "../combinators/xform";

/**
* Stores number of children as result, then discards children. Also see
* {@link count}.
*
* @param scope
*/
export const xfCount: ScopeTransform<any> = (scope) => {
scope!.result = scope!.children ? scope!.children.length : 0;
scope!.children = null;
return scope;
};

/**
* Syntax sugar for `xform(parser, xfCount)`.
*
* @param parser
*/
export const count = <T>(parser: Parser<T>) => xform(parser, xfCount);

0 comments on commit 056ae08

Please sign in to comment.