closest to input

by black strings

HTML

<div id="dataDiv"></div>
<div id="resultEarly"></div>
<div id="resultLatest"></div>

CSS

body {
  background-color: #222;
}

JavaScript

// 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
     ...