metricTree.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. export interface TreeNode {
  2. name: string;
  3. children: TreeNode[];
  4. }
  5. /*
  6. * Builds a nested tree like
  7. * [
  8. * {
  9. * name: 'A',
  10. * children: [
  11. * { name: 'AA', children: [] },
  12. * { name: 'AB', children: [] },
  13. * ]
  14. * }
  15. * ]
  16. */
  17. function buildMetricTree(parent: string, depth: number): TreeNode[] {
  18. const chars = ['A', 'B', 'C'];
  19. const children: TreeNode[] = [];
  20. if (depth > 3) {
  21. return [];
  22. }
  23. for (const letter of chars) {
  24. const nodeName = `${parent}${letter}`;
  25. children.push({
  26. name: nodeName,
  27. children: buildMetricTree(nodeName, depth + 1),
  28. });
  29. }
  30. return children;
  31. }
  32. function queryTree(children: TreeNode[], query: string[], queryIndex: number): TreeNode[] {
  33. if (query[queryIndex] === '*') {
  34. return children;
  35. }
  36. const nodeQuery = query[queryIndex];
  37. let result: TreeNode[] = [];
  38. let namesToMatch = [nodeQuery];
  39. // handle glob queries
  40. if (nodeQuery.startsWith('{')) {
  41. namesToMatch = nodeQuery.replace(/\{|\}/g, '').split(',');
  42. }
  43. for (const node of children) {
  44. for (const nameToMatch of namesToMatch) {
  45. if (node.name === nameToMatch) {
  46. result = result.concat(queryTree(node.children, query, queryIndex + 1));
  47. }
  48. }
  49. }
  50. return result;
  51. }
  52. export function queryMetricTree(query: string): TreeNode[] {
  53. const children = buildMetricTree('', 0);
  54. return queryTree(children, query.split('.'), 0);
  55. }