JSFiddle - React, Tailwind, and code Playground
by tankchintan
HTML
<div id="result"></div>
JavaScript
var PAGE_APP = {
errorVal: undefined,
resultDOM: document.getElementById("result"),
properties: {
timestamps: [],
lastTime: ""
},
getChunk: function(timestamps, lastTime) {
var self = PAGE_APP;
self.properties = {
timestamps: timestamps,
lastTime: lastTime
};
var searchStartBound = 0
var searchStopBound = self.properties.timestamps.length
var searchSpaceMiddleIndex = undefined;
while (true) {
/*
* If only one element remain in the search space, then need to make a decision re: whether
* it fits the criteria of "chunk index found" or not.
* */
if (searchStartBound - searchStopBound === -1) {
//If lastTime is bigger or same then we got a winner
if (self.properties.timestamps[searchStartBound] <= self.properties.lastTime) {
return searchStartBound;
} else {
return self.errorVal;
}
}
//Used to split the search space
searchSpaceMiddleIndex = (searchStartBound + searchStopBound) / 2;
/*
* Since the input is a sorted array it is guaranteed that the timestamp we are looking for
* exists in one or the other split search space, if at all.
* */
if (self.properties.timestamps[searchSpaceMiddleIndex] === self.properties.lastTime) {
//If an exact match, we got a winner!
return searchSpaceMiddleIndex;
} else if (self.properties.timestamps[searchSpaceMiddleIndex] > self.properties.lastTime) {
/*
* If the middle timestamp is bigger than last time then search in the smaller space
* prior to the current middle index
* */
searchStopBound = searchSpaceMiddleIndex;
} else {
searchStartBound = searchSpaceMiddleIndex;
}
...