UNPKG

react-native-chart-kit

Version:

Beautiful React Native charts for dashboards, reports, and data-rich mobile apps.

50 lines (49 loc) 2.46 kB
const defaultLabelKey = "name"; const defaultColorKey = "color"; const defaultFormatValue = (value) => String(value); const defaultFormatPercentage = (percentage) => `${Math.round(percentage * 100)}%`; const getStringValue = (value, fallback) => typeof value === "string" && value.length > 0 ? value : fallback; const getColorValue = (value, fallback) => typeof value === "string" && value.length > 0 ? value : fallback; const getPieValue = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null; const getMaxRow = (rows) => rows.reduce((max, row) => typeof row.value === "number" && (!max || row.value > (max.value ?? 0)) ? row : max, undefined); export const getPieChartDataTable = ({ colorKey, colors, data, formatPercentage = defaultFormatPercentage, formatValue = defaultFormatValue, labelKey, valueKey }) => { const values = data.map((item) => getPieValue(item[valueKey])); const total = values.reduce((sum, value) => (value === null ? sum : sum + value), 0); return { total, rows: data.map((item, index) => { const value = values[index] ?? null; const percentage = value !== null && total > 0 ? value / total : 0; const color = getColorValue(item[colorKey ?? defaultColorKey], colors?.[index]); const row = { formattedValue: value === null ? "No value" : formatValue(value), index, label: getStringValue(item[labelKey ?? defaultLabelKey], `Slice ${index + 1}`), percentage, percentageLabel: formatPercentage(percentage), raw: item, value }; if (color !== undefined) { row.color = color; } return row; }) }; }; export const getPieChartAccessibilitySummary = (input) => { const table = getPieChartDataTable(input); const definedRows = table.rows.filter((row) => row.value !== null); if (definedRows.length === 0) { return "Pie chart with no defined slices."; } const maxRow = getMaxRow(definedRows); const intro = `Pie chart with ${definedRows.length} ${definedRows.length === 1 ? "slice" : "slices"}. Total ${input.formatValue?.(table.total) ?? defaultFormatValue(table.total)}.`; return maxRow ? `${intro} Largest slice is ${maxRow.label} at ${maxRow.percentageLabel}.` : intro; };