metricTree.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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 > 5) {
  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 (queryIndex >= query.length) {
  34. return children;
  35. }
  36. if (query[queryIndex] === '*') {
  37. return children;
  38. }
  39. const nodeQuery = query[queryIndex];
  40. let result: TreeNode[] = [];
  41. let namesToMatch = [nodeQuery];
  42. // handle glob queries
  43. if (nodeQuery.startsWith('{')) {
  44. namesToMatch = nodeQuery.replace(/\{|\}/g, '').split(',');
  45. }
  46. for (const node of children) {
  47. for (const nameToMatch of namesToMatch) {
  48. if (nameToMatch.indexOf('*') !== -1) {
  49. const pattern = nameToMatch.replace('*', '');
  50. const regex = new RegExp(`^${pattern}.*`, 'gi');
  51. if (regex.test(node.name)) {
  52. result = result.concat(queryTree([node], query, queryIndex + 1));
  53. }
  54. } else if (node.name === nameToMatch) {
  55. result = result.concat(queryTree(node.children, query, queryIndex + 1));
  56. }
  57. }
  58. }
  59. return result;
  60. }
  61. export function queryMetricTree(query: string): TreeNode[] {
  62. if (query.indexOf('value') === 0) {
  63. return [{ name: query, children: [] }];
  64. }
  65. const children = buildMetricTree('', 0);
  66. return queryTree(children, query.split('.'), 0);
  67. }