roll-parser - v3.4.0
    Preparing search index...

    Function parse

    • Parses a dice notation string into an ASTNode tree, lexing it first.

      evaluate never mutates the AST, so parse once and evaluate many times when rolling the same notation repeatedly — that skips the lexer and parser on every roll after the first. Use parse alone to validate notation without consuming randomness.

      Parameters

      • notation: string

        The dice notation to parse

      Returns ASTNode

      The root AST node, with start/end spans on every node

      If the input contains invalid characters

      If the input has invalid syntax

      INVALID_NOTATION_TYPE when notation is not a string — raised before lexing, so it carries no position

      import { parse } from 'roll-parser';

      parse('2d6+3');
      // {
      // type: 'BinaryOp', operator: '+', start: 0, end: 5,
      // left: {
      // type: 'Dice', start: 0, end: 3,
      // count: { type: 'Literal', value: 2, start: 0, end: 1 },
      // sides: { type: 'Literal', value: 6, start: 2, end: 3 },
      // },
      // right: { type: 'Literal', value: 3, start: 4, end: 5 },
      // }

      count and sides are full nodes, not numbers — that is what makes computed dice like (1d4)d6 expressible.

      import { evaluate, parse, SeededRNG } from 'roll-parser';

      const ast = parse('4d6kh3');
      const rng = new SeededRNG('demo');
      const scores = Array.from({ length: 6 }, () => evaluate(ast, rng).total);