11import React , { useEffect , useRef } from 'react' ;
2- import {
3- Chart ,
4- ArcElement ,
5- Legend ,
6- PieController ,
7- Tooltip
8- } from 'chart.js' ;
2+ import { ArcElement , Chart , Legend , PieController , Tooltip } from 'chart.js' ;
93
104Chart . register ( ArcElement , Legend , PieController , Tooltip ) ;
115
@@ -21,14 +15,12 @@ const colors = [
2115 "#999999"
2216] ;
2317
24- export default function PieChart ( props ) {
18+ export default function PieChart ( props : { demographics : [ ] , fieldName : string , cutout ?: string , collapseBelow ?: number } ) {
2519 const canvas = useRef ( null ) ;
2620
27- const { demographics } = props ;
28- const { fieldName } = props ;
29- const { cutout } = props || 0 ;
21+ const { demographics, fieldName, cutout = '0' , collapseBelow = 0 } = props ;
3022
31- const collectedData = demographics . reduce ( ( acc , curr ) => {
23+ const collectedData = demographics . reduce ( ( acc , curr ) => {
3224 const value = curr [ fieldName ] === null ? 'Unknown' : curr [ fieldName ] ;
3325 if ( acc [ value ] ) {
3426 acc [ value ] = acc [ value ] + 1 ;
@@ -37,7 +29,31 @@ export default function PieChart(props) {
3729 }
3830
3931 return acc ;
40- } , { } ) ;
32+ } , new Map < string , bigint > ( ) )
33+
34+ if ( collapseBelow ) {
35+ const total = Object . keys ( collectedData ) . reduce ( ( sum , keyName ) => {
36+ sum += collectedData [ keyName ]
37+
38+ return sum
39+ } , 0 )
40+
41+ const otherValue = Object . keys ( collectedData ) . reduce ( ( sum , keyName ) => {
42+ const val = collectedData [ keyName ]
43+ const fraction = val / total
44+ if ( fraction < collapseBelow ) {
45+ delete collectedData [ keyName ]
46+ sum += val
47+ }
48+
49+ return sum
50+ } , 0 )
51+
52+ if ( otherValue ) {
53+ collectedData [ 'Other' ] = otherValue
54+ }
55+ }
56+
4157 const labels = Object . keys ( collectedData ) . sort ( Intl . Collator ( ) . compare ) ;
4258 const data = labels . map ( label => collectedData [ label ] ) ;
4359
0 commit comments