utils.tsx 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import {ColumnType} from 'sentry/utils/discover/fields';
  2. import {getDuration} from 'sentry/utils/formatters';
  3. import {HistogramData} from './types';
  4. export function getBucketWidth(data: HistogramData) {
  5. // We can assume that all buckets are of equal width, use the first two
  6. // buckets to get the width. The value of each histogram function indicates
  7. // the beginning of the bucket.
  8. return data.length >= 2 ? data[1].bin - data[0].bin : 0;
  9. }
  10. export function computeBuckets(data: HistogramData) {
  11. const width = getBucketWidth(data);
  12. return data.map(item => {
  13. const bucket = item.bin;
  14. return {
  15. start: bucket,
  16. end: bucket + width,
  17. };
  18. });
  19. }
  20. export function formatHistogramData(
  21. data: HistogramData,
  22. {
  23. precision,
  24. type,
  25. additionalFieldsFn,
  26. }: {
  27. additionalFieldsFn?: any;
  28. precision?: number;
  29. type?: ColumnType;
  30. } = {}
  31. ) {
  32. const formatter = (value: number): string => {
  33. switch (type) {
  34. case 'duration':
  35. const decimalPlaces = precision ?? (value < 1000 ? 0 : 3);
  36. return getDuration(value / 1000, decimalPlaces, true);
  37. case 'number':
  38. // This is trying to avoid some of potential rounding errors that cause bins
  39. // have the same label, if the number of bins doesn't visually match what is
  40. // expected, check that this rounding is correct. If this issue persists,
  41. // consider formatting the bin as a string in the response
  42. const factor = 10 ** (precision ?? 0);
  43. return (Math.round((value + Number.EPSILON) * factor) / factor).toLocaleString();
  44. default:
  45. throw new Error(`Unable to format type: ${type}`);
  46. }
  47. };
  48. return data.map(item => {
  49. return {
  50. value: item.count,
  51. name: formatter(item.bin),
  52. ...(additionalFieldsFn?.(item.bin) ?? {}),
  53. };
  54. });
  55. }