Last active
July 24, 2016 16:54
-
-
Save asduser/9a924c075971f66154ca71956235959a to your computer and use it in GitHub Desktop.
Closest number in array
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
/* | |
* @param num {number} - required digit | |
* @param arr {array} - input set of digits | |
* @returns {number} - closest item | |
*/ | |
function closest (num, arr) { | |
try { | |
if(isNaN(num)){ | |
throw new Error("The 1st argument is not a number."); | |
} | |
if(arr.constructor !== Array){ | |
throw new Error("The 2nd argument is not an array of numbers."); | |
} | |
} catch (message) { | |
console.error(message); | |
return null; | |
} | |
var element = arr[0]; | |
var difference = Math.abs(num - element); | |
var len = arr.length; | |
for (var i = 0; i < len; i++) { | |
var newDifference = Math.abs (num - arr[i]); | |
if (newDifference < difference) { | |
difference = newDifference; | |
element = arr[i]; | |
} | |
} | |
return element; | |
} | |
// Configuration. | |
var arr = [43,54,65,3,4,4,232,11], number = 9; | |
// Use timer. | |
console.time("t1"); | |
for (var i=0; i<1; i++) { | |
alert( closest(number, arr) ); | |
} | |
console.timeEnd("t1"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment