Is it possible to combine all the functions into a single function? I'm providing my fiddle as well.
I am trying to test it for different scenarios.. but I am not sure how to combine all the scenarios into one..
var myNumbersToSort = [null, -1, 2, 0.001, -3, 4, 0.3,1,-0.0001];
function getClosestToZero(set) {
if(0 === set.length) return null;
var closest = set[0], result = 0;
for(var i in set) {
var next = set[i];
if(Math.abs(closest) > Math.abs(next)) {
result = i;
closest = next;
}
}
return closest;
}
function getClosestToZeroWithNaN(set) {
var closest;
if(set instanceof Array) {
for(var i = 0; i < set.length; i++) {
var val = set[i];
if(!isNaN(val)){
val = Number(val);
var absVal = Math.abs(val);
if(typeof closest == 'undefined' || Math.abs(closest) > absVal) {
closest = val;
}
}
}
}
return closest;
}
function getClosestToZeroOnlyNumbers(set) {
var closest;
if(set instanceof Array) {
for(var i = 0; i < set.length; i++) {
var val = set[i];
if(typeof val == "number"){
var absVal = Math.abs(val);
if(typeof closest == 'undefined' || Math.abs(closest) > absVal) {
closest = val;
}
}
}
}
return closest;
}
document.getElementById('output').innerHTML = (getClosestToZeroOnlyNumbers(myNumbersToSort));