parser.ts 712 B

123456789101112131415161718192021222324252627
  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 (
  7. treeToList(tree)
  8. // Remove empty (optional) tokens
  9. .filter(Boolean)
  10. );
  11. }
  12. export function joinTokens(tokens: TokenList): string {
  13. return tokens.map(token => token.content).join('');
  14. }
  15. function treeToList(tree: TokenTree): TokenList {
  16. return tree.reduce<TokenList>((acc, token) => {
  17. if (Array.isArray(token)) {
  18. return acc.concat(treeToList(token));
  19. }
  20. return acc.concat(token);
  21. }, []);
  22. }