import { arrayStream } from "polar-shared/src/util/ArrayStreams" ; import { StringComparators } from "polar-shared/src/util/StringComparators" ; import { TagFilters } from "polar-shared/src/tags/TagFilters" ; import { NumberComparators } from "polar-shared/src/util/NumberComparators" ; import { Tag } from "polar-shared/src/tags/Tags" ; export namespace Sorting { export type Order = 'asc' | 'desc' ; /**
     * Convert value from F and to T
     */ export type TypeConverter < F , T > = ( from : F ) => T ; export type PrimitiveConverter < V > = ( value : V ) => number | string ; export function reverse ( order ) { return order === 'asc' ? 'desc' : 'asc' ; } function createComparatorWithOrderBy < F , T > ( a , b , order , orderBy , converter ) { const toVal = ( value ) : number | string => { if ( value === undefined || value === null ) { return "" ; } if ( typeof value === 'number' || typeof value === 'string' ) { return value ; } if ( orderBy === 'tags' ) { type TagMap = { [ id ] : Tag ; } ; const tagMap = value ; return Object . values ( tagMap ) . filter ( TagFilters . onlyRegular ) . map ( current => current . label . toLowerCase ( ) ) . sort ( ) . join ( ', ' ) ; } function toDictionaryValue ( ) { const dict = value ; return Object . values ( dict ) . map ( current => current . toString ( ) . toLowerCase ( ) ) . sort ( ) . join ( ', ' ) ; } return toDictionaryValue ( ) ; } ; const aVal = toVal ( < any > converter ( a ) [ orderBy ] ) ; const bVal = toVal ( < any > converter ( b ) [ orderBy ] ) ; if ( typeof aVal === 'number' ) { return NumberComparators . create ( aVal as number , bVal as number , order ) ; } return StringComparators . comparatorWithEmptyStringsLast ( < string > aVal , < string > bVal , order ) ; } export function createComparator < F , T > ( order , orderBy , converter ) { return ( a , b ) => createComparatorWithOrderBy < F , T > ( a , b , order , orderBy , converter ) ; } export function stableSort < T > ( array , comparator ) { return arrayStream ( array ) . sort ( comparator ) . collect ( ) ; } }