Reputation: 1902
I'm writing a simple function in Javascript that returns the largest in an array of numbers and I have a bunch of test data but I cannot for the life of me figure out why 2 of the tests failed.
My largest in list function:
function largestInList(list) {
var largest = Number.MIN_VALUE;
for (var i = 0; i < list.length; i++) {
if (largest <= list[i])
largest = list[i];
}
return largest;
}
My Tests
it("Return the largest in a list", function() {
expect(largestInList).toBeDefined();
expect(largestInList([])).toEqual(Number.MIN_VALUE);
expect(largestInList([-11])).toEqual(-11);
expect(largestInList([-1, -3])).toEqual(-1);
expect(largestInList([3, -1])).toEqual(3);
expect(largestInList([3, -1, 8])).toEqual(8);
expect(largestInList([4, 9, -1, 9, 8])).toEqual(9);
expect(largestInList([3, 61, 8])).toEqual(61);
expect(largestInList([3, 61, 8, 333, -1])).toEqual(333);
});
These two lines failed but I cannot figure out why?
expect(largestInList([-11])).toEqual(-11);
expect(largestInList([-1, -3])).toEqual(-1);
Error:
Expected 5e-324 to equal -11
Expected 5e-324 to equal -1
I'm not a math person but if my assumption is correct -11 < -1 and 5e-324 => 5 x 10 raised to the power of -324 (which technically should be a lot smaller than -11 or -1)
Upvotes: 1
Views: 307
Reputation: 160251
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MIN_VALUE
The Number.MIN_VALUE property represents the smallest positive numeric value representable in JavaScript.
[...]
The MIN_VALUE property is the number closest to 0, not the most negative number, that JavaScript can represent.
5e-325
isn't a negative number.
Maybe negative infinity instead? It kind of depends on what you're doing with the result.
Upvotes: 1