QueryBlock.utils.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import { ChartConfig } from '@/components/interfaces/SQLEditor/UtilityPanel/ChartConfig'
  2. export const checkHasNonPositiveValues = (data: Record<string, unknown>[], key: string): boolean =>
  3. data.some((row) => (row[key] as number) <= 0)
  4. export const formatYAxisTick = (value: number): string => {
  5. if (Math.abs(value) >= 1_000_000) {
  6. const n = value / 1_000_000
  7. return `${Number.isInteger(n) ? n : n.toFixed(1)}M`
  8. }
  9. if (Math.abs(value) >= 1_000) {
  10. const n = value / 1_000
  11. return `${Number.isInteger(n) ? n : n.toFixed(1)}K`
  12. }
  13. if (value !== 0 && Math.abs(value) < 1) {
  14. return parseFloat(value.toFixed(2)).toString()
  15. }
  16. if (!Number.isInteger(value)) {
  17. return parseFloat(value.toFixed(1)).toString()
  18. }
  19. return String(value)
  20. }
  21. export const computeYAxisWidth = (
  22. data: Record<string, unknown>[],
  23. key: string,
  24. {
  25. isLogScale = false,
  26. isPercentage = false,
  27. }: { isLogScale?: boolean; isPercentage?: boolean } = {}
  28. ): number => {
  29. if (isLogScale) return 52
  30. if (isPercentage) return Math.max(36, (3 + 1) * 8) // max tick is "100"
  31. const maxMagnitude =
  32. data.length > 0 ? Math.max(...data.map((d) => Math.abs(Number(d[key]) || 0))) : 0
  33. return Math.max(36, (formatYAxisTick(maxMagnitude).length + 1) * 8)
  34. }
  35. export const formatLogTick = (value: number): string => {
  36. if (value >= 1_000_000)
  37. return `${(value / 1_000_000).toLocaleString(undefined, { maximumFractionDigits: 1 })}M`
  38. if (value >= 1_000)
  39. return `${(value / 1_000).toLocaleString(undefined, { maximumFractionDigits: 1 })}k`
  40. return value.toLocaleString()
  41. }
  42. export const getCumulativeResults = (results: { rows: any[] }, config: ChartConfig) => {
  43. if (!results?.rows?.length) {
  44. return []
  45. }
  46. const cumulativeResults = results.rows.reduce((acc, row) => {
  47. const prev = acc[acc.length - 1] || {}
  48. const next = {
  49. ...row,
  50. [config.yKey]: (prev[config.yKey] || 0) + row[config.yKey],
  51. }
  52. return [...acc, next]
  53. }, [])
  54. return cumulativeResults
  55. }