Java Reference
In-Depth Information
it("should say a non-integer is not prime", function() {
expect(isPrime(decimal)).toBe(false);
});
If you reload the SpecRunner.html file, you'll see that the tests for the factorsOf()
function fail as expected, but the tests for the isPrime() function pass. This is by a
happy accident because the factorsOf() function is returning an empty array that is not
of length 2 , so false is returned as expected.
Let's try and make all the tests pass by throwing some exceptions in the factorsOf()
function. Change the factorsOf() function to the following in numberCruncher.js:
src/numberCruncher.js (incomplete, excerpt)
function factorsOf(n) {
if (n < 0) {
throw new RangeError("Argument Error: Number must be
positive");
}
if (Math.floor(n) !== n) {
throw new RangeError("Argument Error: Number must be
an
integer");
}
var factors = [];
for (var i=1 , max = Math.sqrt(n); i <= max ; i++) {
if (n%i === 0){
factors.push(i,n/i);
}
}
return factors.sort(function(a,b) { return a > b; });
}
Now the function checks to see if a negative number or non-integer has been provided as
an argument and throws an exception in both cases. Let's run our tests again by refreshing
Search WWH ::




Custom Search