import { sortBy } from 'lodash' ; interface PriorityValue { readonly priority : number ; } /**
 * Immutable map that ensures entries are always in descending order based on
 * the values 'priority' property.
 */ export class PriorityMap < K , V extends PriorityValue > implements Iterable < [ K , V ] > { private readonly map : ReadonlyMap < K , V > ; constructor ( map ? ) { this . map = map ? new Map ( sortEntries ( map ) ) : new Map ( ) ; } public add ( key , value ) { return new PriorityMap < K , V > ( new Map < K , V > ( sortEntries ( [ ... this . map , [ key , value ] ] ) ) ) ; } public remove ( key ) { return new PriorityMap < K , V > ( new Map < K , V > ( [ ... this . map ] . filter ( ( [ itemKey ] ) => itemKey !== key ) ) ) ; } public has ( key ) { return this . map . has ( key ) ; } public [ Symbol . iterator ] ( ) { return this . map [ Symbol . iterator ] ( ) ; } public values ( ) { return this . map . values ( ) ; } } const sortEntries = < K , V extends PriorityValue > ( map ) : Iterable < [ K , V ] > => sortBy ( [ ... map ] as Array < [ K , V ] > , '1.priority' ) . reverse ( ) ;