import React , { createContext , useContext , useMemo , useState } from 'react' ; export type SortDirection = 'asc' | 'desc' ; interface Sort { columnId : number ; direction : SortDirection ; accessorValue ? : ( data : any ) => string ; compareFn ? : ( a : any , b : any , direction : SortDirection ) => number ; handleSort ? : ( direction : SortDirection ) => void ; } interface ContextInterface { sort ? : Sort ; setSort : React . Dispatch < React . SetStateAction < Sort | undefined > > ; } const SortContext = createContext < ContextInterface > ( { sort : undefined , setSort : ( ) => { } , } ) ; export function SortProvider ( { children } ) { const [ sort , setSort ] = useState < Sort | undefined > ( undefined ) ; const contextValue = useMemo ( ( ) => { return { sort , setSort } ; } , [ sort , setSort ] ) ; return ( < SortContext . Provider value = { contextValue } > { children } < /SortContext.Provider>); } export function useSortContext ( ) { return useContext ( SortContext ) ; } const alphanumericCollator = new Intl . Collator ( undefined , { numeric : true , sensitivity : 'base' , } ) ; export const getDataComparisonFunction = < T extends { } > ( { direction , accessorValue , compareFn , } ) => { if ( accessorValue ) { return ( a , b ) => { const aVal = accessorValue ( a ) ; const bVal = accessorValue ( b ) ; if ( direction !== 'desc' ) { return alphanumericCollator . compare ( aVal , bVal ) ; } return alphanumericCollator . compare ( bVal , aVal ) ; } ; } if ( compareFn ) { return ( a , b ) => compareFn ( a , b , direction ) ; } console . error ( 'Error getting Table data comparison function. Please supply either an `accessorValue` or `compareFn`' ) ; } ;