Skip to content

Instantly share code, notes, and snippets.

@neftaly
Last active November 30, 2015 14:22
Show Gist options
  • Select an option

  • Save neftaly/91757076d0de83efbc9b to your computer and use it in GitHub Desktop.

Select an option

Save neftaly/91757076d0de83efbc9b to your computer and use it in GitHub Desktop.
Binary search on time-series database
// inst: unix epoch
const hist = {
"channel1": [
{ inst: 10000, id: "a" },
{ inst: 20000, id: "b" },
{ inst: 30000, id: "c" },
{ inst: 30000, id: "d" },
{ inst: 40000, id: "e" }
]
};
// Search ordered time-series array for any events since last.
// Results include last, in case any events were simultaneous.
const updates = (array, last) => {
const value = obj => obj.inst;
const search = (min, max) => {
if (min > max) {
return min;
}
const mid = Math.floor((min + max) / 2);
const tryLater = value(array[mid]) < last;
return tryLater ? search(mid + 1, max) : search(min, mid - 1);
};
return array.slice(search(0, array.length));
};
updates(hist.channel1, 30000); // returns c, d and e
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment