binarySearchSpec.js 1.97 KB
Newer Older
Manggar Mahardhika's avatar
Manggar Mahardhika committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
import { binarySearch } from "../../Source/Cesium.js";

describe("Core/binarySearch", function () {
  it("can perform a binary search for 0", function () {
    var array = [0, 1, 2, 3, 4, 5, 6, 7];
    var toFind = 0;
    var index = binarySearch(array, toFind, function (a, b) {
      return a - b;
    });
    expect(index).toEqual(0);
  });

  it("can perform a binary search for item in the list", function () {
    var array = [0, 1, 2, 3, 4, 5, 6, 7];
    var toFind = 7;
    var index = binarySearch(array, toFind, function (a, b) {
      return a - b;
    });
    expect(index).toEqual(7);
  });

  it("can perform a binary search for item in between two items in the list", function () {
    var array = [0, 1, 2, 3, 4, 5, 6, 7];
    var toFind = 3.5;
    var index = binarySearch(array, toFind, function (a, b) {
      return a - b;
    });
    expect(~index).toEqual(4);
  });

  it("can perform a binary search for item before all items in the list", function () {
    var array = [0, 1, 2, 3, 4, 5, 6, 7];
    var toFind = -2;
    var index = binarySearch(array, toFind, function (a, b) {
      return a - b;
    });
    expect(~index).toEqual(0);
  });

  it("can perform a binary search for item after all items in the list", function () {
    var array = [0, 1, 2, 3, 4, 5, 6, 7];
    var toFind = 12;
    var index = binarySearch(array, toFind, function (a, b) {
      return a - b;
    });
    expect(~index).toEqual(8);
  });

  function dummy() {
    return true;
  }

  it("throws an exception if array is missing", function () {
    expect(function () {
      binarySearch(undefined, 1, dummy);
    }).toThrowDeveloperError();
  });

  it("throws an exception if itemToFind is missing", function () {
    expect(function () {
      binarySearch([0, 1, 2], undefined, dummy);
    }).toThrowDeveloperError();
  });

  it("throws an exception if comparator is missing", function () {
    expect(function () {
      binarySearch([0, 1, 2], 1, undefined);
    }).toThrowDeveloperError();
  });
});