parser.ts 639 B

1234567891011121314151617181920212223
  1. import type {Token, TokenList} from 'sentry/views/ddm/formulaParser/types';
  2. import grammar from './formula.pegjs';
  3. type TokenTree = Array<Token | TokenTree>;
  4. export function parseFormula(formula: string): TokenList {
  5. const tree = grammar.parse(formula) as TokenTree;
  6. return treeToList(tree);
  7. }
  8. export function joinTokens(tokens: TokenList): string {
  9. return tokens.map(token => token.content).join('');
  10. }
  11. function treeToList(tree: TokenTree): TokenList {
  12. return tree.reduce<TokenList>((acc, token) => {
  13. if (Array.isArray(token)) {
  14. return acc.concat(treeToList(token));
  15. }
  16. return acc.concat(token);
  17. }, []);
  18. }