| 1 | /**
|
|---|
| 2 | * Finds the index of the first occurrence of a value in a sorted array, similar to how `Array#indexOf` works, but specifically for sorted arrays.
|
|---|
| 3 | *
|
|---|
| 4 | * Make sure to provide a sorted array to this function, as it uses a binary search to quickly find the index.
|
|---|
| 5 | *
|
|---|
| 6 | * @param {ArrayLike<T> | null | undefined} array The sorted array to inspect.
|
|---|
| 7 | * @param {T} value The value to search for.
|
|---|
| 8 | * @returns {number} Returns the index of the matched value, else -1.
|
|---|
| 9 | *
|
|---|
| 10 | * @example
|
|---|
| 11 | * const numbers = [1, 2, 3, 4, 5];
|
|---|
| 12 | * sortedIndexOf(numbers, 11); // Return value: 0
|
|---|
| 13 | * sortedIndexOf(numbers, 30); // Return value: -1
|
|---|
| 14 | *
|
|---|
| 15 | * // If the value is duplicated, it returns the first index of the value.
|
|---|
| 16 | * const duplicateNumbers = [1, 2, 2, 3, 3, 3, 4];
|
|---|
| 17 | * sortedIndexOf(duplicateNumbers, 3); // Return value: 3
|
|---|
| 18 | *
|
|---|
| 19 | * // If the array is unsorted, it can return the wrong index.
|
|---|
| 20 | * const unSortedArray = [55, 33, 22, 11, 44];
|
|---|
| 21 | * sortedIndexOf(unSortedArray, 11); // Return value: -1
|
|---|
| 22 | *
|
|---|
| 23 | * // -0 and 0 are treated the same
|
|---|
| 24 | * const mixedZeroArray = [-0, 0];
|
|---|
| 25 | * sortedIndexOf(mixedZeroArray, 0); // Return value: 0
|
|---|
| 26 | * sortedIndexOf(mixedZeroArray, -0); // Return value: 0
|
|---|
| 27 | *
|
|---|
| 28 | * // It works with array-like objects
|
|---|
| 29 | * const arrayLike = { length: 3, 0: 10, 1: 20, 2: 30 };
|
|---|
| 30 | * sortedIndexOf(arrayLike, 20); // Return value: 1
|
|---|
| 31 | */
|
|---|
| 32 | declare function sortedIndexOf<T>(array: ArrayLike<T> | null | undefined, value: T): number;
|
|---|
| 33 |
|
|---|
| 34 | export { sortedIndexOf };
|
|---|