Java Reference
In-Depth Information
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; });
}
We'll also sort the array at the end using the
sort()
method with a callback we saw in
Refresh SpecRunner.html to confirm that the tests still pass.
Now that our tests are passing and our code has been refactored, it's time to add some more
functionality. Let's write another function called
isPrime()
that will return
true
if a
number is prime and
false
if it isn't. Let's start by writing the test by adding the follow-
ing code to the numberSpec.js file:
spec/numberSpec.js (incomplete)
describe("The isPrime() function", function() {
it("should say 2 is prime", function() {
expect(isPrime(2)).toBe(true);
});
it("should say 10 is not prime", function() {
expect(isPrime(10)).not.toBe(true);
});
});
We're using a new
describe
block because we are testing a different function. This
block has two specs―one to check whether
true
is returned when a prime number (
2
)
is provided as an argument and another to check that
true
is not returned if a non-prime
number (
10
) is given as an argument. These specs use the
toBe()
matcher, which allows
you to check if something is
true
or
false
. Note the nice use of negation using the
not
