@@ -500,7 +500,7 @@ namespace ts {
500500 */
501501 export function append < T > ( to : T [ ] | undefined , value : T | undefined ) : T [ ] | undefined {
502502 if ( value === undefined ) return to ;
503- if ( to === undefined ) to = [ ] ;
503+ if ( to === undefined ) return [ value ] ;
504504 to . push ( value ) ;
505505 return to ;
506506 }
@@ -521,6 +521,16 @@ namespace ts {
521521 return to ;
522522 }
523523
524+ /**
525+ * Stable sort of an array. Elements equal to each other maintain their relative position in the array.
526+ */
527+ export function stableSort < T > ( array : T [ ] , comparer : ( x : T , y : T ) => Comparison = compareValues ) {
528+ return array
529+ . map ( ( _ , i ) => i ) // create array of indices
530+ . sort ( ( x , y ) => comparer ( array [ x ] , array [ y ] ) || compareValues ( x , y ) ) // sort indices by value then position
531+ . map ( i => array [ i ] ) ; // get sorted array
532+ }
533+
524534 export function rangeEquals < T > ( array1 : T [ ] , array2 : T [ ] , pos : number , end : number ) {
525535 while ( pos < end ) {
526536 if ( array1 [ pos ] !== array2 [ pos ] ) {
@@ -1984,6 +1994,17 @@ namespace ts {
19841994 }
19851995
19861996 /** Remove an item from an array, moving everything to its right one space left. */
1997+ export function orderedRemoveItem < T > ( array : T [ ] , item : T ) : boolean {
1998+ for ( let i = 0 ; i < array . length ; i ++ ) {
1999+ if ( array [ i ] === item ) {
2000+ orderedRemoveItemAt ( array , i ) ;
2001+ return true ;
2002+ }
2003+ }
2004+ return false ;
2005+ }
2006+
2007+ /** Remove an item by index from an array, moving everything to its right one space left. */
19872008 export function orderedRemoveItemAt < T > ( array : T [ ] , index : number ) : void {
19882009 // This seems to be faster than either `array.splice(i, 1)` or `array.copyWithin(i, i+ 1)`.
19892010 for ( let i = index ; i < array . length - 1 ; i ++ ) {
0 commit comments