Java Reference
In-Depth Information
Consider the code in Listing 4-2. It defines two functions:
isInteger()
and
factorial()
. The
isInteger()
function returns
true
if its argument is an integer;
otherwise, it returns
false
. The
factorial()
function computes and returns the
factorial of a natural number. It throws a
TypeError
is its argument is not a number and a
RangeError
if its argument is not a number greater than or equal to 1.
Listing 4-2.
The Contents of the factorial.js file
// factorial.js
// Returns true if n is an integer. Otherwise, returns false.
function isInteger(n) {
return typeof n === "number" && isFinite(n) && n%1 === 0;
}
// Define a function that computes and returns the factorial of an integer
function factorial(n) {
if (!isInteger(n)) {
throw new TypeError(
"The number must be an integer. Found:" + n);
}
if(n < 0) {
throw new RangeError(
"The number must be greater than 0. Found: " + n);
}
var fact = 1;
for(var counter = n; counter > 1; fact *= counter--);
return fact;
}
The program in Listing 4-3 uses the
factorial()
function to compute factorial
for a number and a String. The
load()
function is used to load the program from the
factorial.js
file. The
message
property of the
Error
object (or its subtype) contains the
error message. The program uses the
message
property to display the error message. The
factorial()
function throws a
TypeError
when “Hello” is passed to it as an argument.
The program handles the error and displays the error message.
Listing 4-3.
The Contents of the File factorial_test.js
// factorial_test.js
// Load the factorial.js file that contains the factorial() function
load("factorial.js");
Search WWH ::
Custom Search