@@ -205,3 +205,44 @@ function getTaggedValue(
205
205
${ tagText } ${ text } `) . toJSON ( ) ;
206
206
return value ;
207
207
}
208
+
209
+ /**
210
+ * Find the insertion position (index) of an item in an array with items sorted
211
+ * in ascending order; so that `splice(sortedIndex, 0, item)` would result in
212
+ * maintaining the array's sort-ness. The array can contain duplicates.
213
+ * If the item already exists in the array the index would be of the *last*
214
+ * occurrence of the item.
215
+ *
216
+ * Runs in O(logN) time.
217
+ *
218
+ * MIT License | Copyright (c) 2018 remeda | https://remedajs.com/
219
+ *
220
+ * The implementation is copied from remeda package:
221
+ * https://github.com/remeda/remeda/blob/878206eb3e8ec1c7f1300b1909b7aa629810c8bb/src/sortedLastIndex.ts
222
+ * https://github.com/remeda/remeda/blob/878206eb3e8ec1c7f1300b1909b7aa629810c8bb/src/internal/binarySearchCutoffIndex.ts#L1
223
+ *
224
+ * @param data - The (ascending) sorted array.
225
+ * @param item - The item to insert.
226
+ * @returns Insertion index (In the range 0..data.length).
227
+ * @signature
228
+ * sortedLastIndex(data, item)
229
+ * @example
230
+ * sortedLastIndex(['a','a','b','c','c'], 'c') // => 5
231
+ */
232
+ export function sortedLastIndex < T > ( array : readonly T [ ] , item : T ) : number {
233
+ let lowIndex = 0 ;
234
+ let highIndex = array . length ;
235
+
236
+ while ( lowIndex < highIndex ) {
237
+ const pivotIndex = ( lowIndex + highIndex ) >>> 1 ;
238
+ const pivot = array [ pivotIndex ] ;
239
+
240
+ if ( pivot <= item ) {
241
+ lowIndex = pivotIndex + 1 ;
242
+ } else {
243
+ highIndex = pivotIndex ;
244
+ }
245
+ }
246
+
247
+ return highIndex ;
248
+ }
0 commit comments