param array param element param comparator export function sortedInsert < T > ( array , element , comparator ) { let low = 0 ; let high = array . length - 1 ; let destination = - 1 ; while ( low < high ) { const mid = Math . floor ( ( low + high ) / 2 ) ; const comparison = comparator ( element , array [ mid ] ) ; if ( comparison === 0 ) { destination = mid + 1 ; break ; } if ( comparison < 0 ) { high = mid - 1 ; } else { low = mid + 1 ; } } if ( array . length === 0 ) { destination = 0 ; } else if ( destination < 0 ) { if ( comparator ( element , array [ low ] ) > 0 ) { destination = low + 1 ; } else { destination = low ; } } array . splice ( destination , 0 , element ) ; }