JSFiddle - React, Tailwind, and code Playground

by patrickarlt

JavaScript

function BinarySearchIndex(values) {
  this.values = values;
}

BinarySearchIndex.prototype.query = function(key, query){
  this.values.sort(function(a, b) {
    return a[key] - b[key];
  });

  var minIndex = 0;
  var maxIndex = this.values.length - 1;
  var currentIndex;
  var currentElement;
  var resultIndex;

  while (minIndex <= maxIndex) {
    resultIndex = currentIndex = (minIndex + maxIndex) / 2 | 0;
    currentElement = this.values[currentIndex];

    if (currentElement[key] < query) {
      minIndex = currentIndex + 1;
    }
    else if (currentElement[key] > query) {
      maxIndex = currentIndex - 1;
    }
    else {
      return currentIndex;
    }
  }

  return Math.abs(maxIndex);
}

BinarySearchIndex.prototype.add = function(values){
  this.values  = this.values.concat(values);
}

var bs = new BinarySearchIndex([
  {value: 2},
  {value: 128},
  {value: 8},
  {value: 64},
]);

bs.add([
  {value: 1},
  {value: 4},
  {value: 32},
  {value: 16}
]);

alert(bs.query("value", 1)); // 0
alert(bs.query("value", 2)); // 1
alert(bs.query("value", 3)); // 1
alert(bs.query("value", 5)); // 2
alert(bs.query("value", 18)); // 4
alert(bs.query("value", 200)); // 7