Last active
November 30, 2015 14:22
-
-
Save neftaly/91757076d0de83efbc9b to your computer and use it in GitHub Desktop.
Binary search on time-series database
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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