import { __ } from '@wordpress/i18n'; export interface DataItem { name: string; value: number; color: string; count: number | string; } /** * Keep the `topN` largest items by value and fold the rest into a single "Others" entry. * Keeps a chart readable on sites with many custom post types or many option groups. * @param items * @param topN */ export function collapseToTopN(items: DataItem[], topN: number): DataItem[] { if (items.length <= topN) { return items; } const sorted = [...items].sort((a, b) => b.value - a.value); const head = sorted.slice(0, topN); const tail = sorted.slice(topN); const othersValue = tail.reduce((sum, it) => sum + it.value, 0); const othersCount = tail.reduce( (sum, it) => sum + (typeof it.count === 'number' ? it.count : Number(it.count) || 0), 0 ); return [ ...head, { name: __('Others', 'scotty'), value: Number(othersValue.toFixed(2)), color: 'gray.5', count: othersCount, }, ]; }