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