ator, array, target)[1]; }, /** * Searches for the given target in the given array. * * @param {(a: any, b: any) => number} comparator * A function that takes two arguments and compares them, returning a * negative number if the first should be ordered before the second, * zero if the first and second have the same ordering, or a positive * number if the second should be ordered before the first. The first * argument is always `target`, and the second argument is a value * from the array. * @param {Array} array * An array whose elements are ordered by `comparator`. * @param {any} target * The value to search for. * @returns {Array} An array with two elements. If `target` is found, the first * element is true, and the second element is its index in the array. * If `target` is not found, the first element is false, and the * second element is the index where it may be inserted to keep the * array ordered. */ search(comparator, array, target) { let low = 0; let high = array.length - 1; while (low <= high) { // Thanks to http://jsperf.com/code-review-1480 for this tip. let mid = (low + high) >> 1; let cmp = comparator(target, array[mid]); if (cmp == 0) { return [true, mid]; } if (cmp < 0) { high = mid - 1; } else { low = mid + 1; } } return [false, low]; }, }); PK