// data to simulate
data = [1,3,5,9,7,2];
userInput = 6;
// fire the function
document.getElementById('dataDiv').innerHTML = '[ ' + data + ' ]';
var earlyResult = getClosestEarly(userInput);
var latestResult = getClosestLatest(userInput);
// early result
var earlyResultStr = 'earliest to userInput ' + userInput + ' is ' + earlyResult;
document.getElementById('resultEarly').innerHTML = earlyResultStr;
// late result
var lateResultStr = 'latest to userInput ' + userInput + ' is ' + latestResult;
document.getElementById('resultLatest').innerHTML = lateResultStr;
function getClosestEarly(input){
// temp is our pointer
// it will always points to the closest earliest time to the input
// as it loops, we modify this temp if it is closer than the previous temp
var temp = data[0]; // start at zero of array index (begin)
for(var i=0; i<data.length; i++){
var tempIsLess = false;
var currIsLess = false;
// current element in loop
var curr = data[i];
// use a simple flag to help check if temp is less than input
if(temp < input){
tempIsLess = true;
}
// simple flag to help check if curr is less than input
// if next is greather than input, we shouldn't even do anything
// curr cannot be bigger than input
// since we are trying to getting a value earlier than input
if(curr < input){
currIsLess = true;
}
if(tempIsLess && currIsLess){
// means that both are less than input
// thus we favor the one that has the shortest distance
var tempDistance = Math.abs(input-temp);
var currDistance = Math.abs(input-curr);
if(currDistance < tempDistance){
temp = curr;
}
} else if (currIsLess) {
// means that current is less than input
// and temp is bigger than input
// so we update temp to curr
temp = curr;
} else {
// means that temp is greater than input
// and curr is greater than input
// so we do nothing
...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.