var numberToCompare = 0;
var searchForValueClosestToZero = function(arr) {
var diff = Number.MAX_VALUE, curI, result, tieI;
if (arr.length === 1) {
result = arr[0];
return result;
} else {
for (var i = 0; i< arr.length; i++) {
var val = arr[i];
curDiff = Math.abs(val - numberToCompare);
if (curDiff < diff) {
curI = i;
diff = curDiff;
} else if(curDiff === diff) {
tieI = i;
console.dir({
i:i,
curDiff: curDiff
})
}
}
if(arr[curI] < 0) {
if(typeOf tieI !== 'undefined' && Math.abs(arr[tieI]) === Math.abs(arr[curI])){
result = arr[tieI];
}
} else {
result = arr[curI];
}
return result;
}
return result;
}
//red
describe('Closest to zero exercise', function () {
var list, result;
it('testing function with array of one value', function () {
list = [1] ;
result = searchForValueClosestToZero(list);
expect(result).toBe(1);
});
it('testing function with array of several values not containing negatives', function () {
list = [3, 0, 3, 1, 5, 100] ;
result = searchForValueClosestToZero(list);
expect(result).toBe(0);
});
it('testing function with array of several values containing negatives', function () {
list = [30, -3, 10, 5, 100] ;
result = searchForValueClosestToZero(list);
expect(result).toBe(-3);
});
it('testing function with array with tie', function () {
list = [-3, 30, 3, 10, 5, 100] ;
result = searchForValueClosestToZero(list);
expect(result).toBe(3);
});
it('testing function with empty array', function () {
list = [] ;
result = searchForValueClosestToZero(list);
...
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.