1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
3 * You can obtain one at http://mozilla.org/MPL/2.0/. */
7 this.EXPORTED_SYMBOLS = [
11 this.BinarySearch = Object.freeze({
14 * Returns the index of the given target in the given array or -1 if the
15 * target is not found.
17 * See search() for a description of this function's parameters.
19 * @return The index of `target` in `array` or -1 if `target` is not found.
21 indexOf: function (array, target, comparator) {
22 let [found, idx] = this.search(array, target, comparator);
23 return found ? idx : -1;
27 * Returns the index within the given array where the given target may be
28 * inserted to keep the array ordered.
30 * See search() for a description of this function's parameters.
32 * @return The index in `array` where `target` may be inserted to keep `array`
35 insertionIndexOf: function (array, target, comparator) {
36 return this.search(array, target, comparator)[1];
40 * Searches for the given target in the given array.
43 * An array whose elements are ordered by `comparator`.
45 * The value to search for.
47 * A function that takes two arguments and compares them, returning a
48 * negative number if the first should be ordered before the second,
49 * zero if the first and second have the same ordering, or a positive
50 * number if the second should be ordered before the first. The first
51 * argument is always `target`, and the second argument is a value
53 * @return An array with two elements. If `target` is found, the first
54 * element is true, and the second element is its index in the array.
55 * If `target` is not found, the first element is false, and the
56 * second element is the index where it may be inserted to keep the
59 search: function (array, target, comparator) {
61 let high = array.length - 1;
63 let mid = Math.floor((low + high) / 2);
64 let cmp = comparator(target, array[mid]);