(References: lab08, lab09, lectures 10/30, 11/01, 11/06)
Suppose that we want to build a web page that can do a simple calculation—how much tickets to the upcoming Jon Stewart performance will cost. Tickets for students are $30 each, and tickets for others are $65 each.
Here is the form we will use:

We might first develop a JavaScript function that can take the number of student tickets
and the number of other tickets, and determine the total price.
For example, here is a "stub" for the ticketCalc function:
// ticketCalcStub.js P. Conrad for CISC103 Midterm Exam 2, 11/08/2007 // define a stub for a function that determines the price of a certain // number of tickets to the Jon Stewart concert. // // Consumes: // numST a number, how many student tickets you want ($30 each) // numOT a number, how many other tickets you want ($65 each) // Produces: // totalPrice: the total price for all your tickets // Examples: // js> ticketCalc(1,0) // 30 // js> ticketCalc(0,1) // 65 // js> ticketCalc(0,2) // 130 // js> ticketCalc(2,1) // 125
function ticketCalc(numST, numOT) { return (-42); }
And here is a test script, and the result of running the test script on both a stub function, and a correct function:
// testTicketCalc.js test script for ticketCalc.js
// P. Conrad for CISC103 Midterm Exam 2, 11/08/2007
// test the function ticketCalc()
function testTicketCalc() {
//=======================================
// define the tolerance
//=======================================
// Tolerance is small because calculation is simple--
// because we expect results to be very accurate
var tolerance = 0.0001;
//===================
// Run the tests
//===================
// Test 1
var expected = 125;
var actual = ticketCalc(2,1);
var diff = Math.abs(expected-actual);
if (diff < tolerance)
{
print('test 1 passed');
}
else
{
print('test 1 failed');
print('expected=' + expected);
print('actual=' + actual);
}
// Test 2
expected = 160;
actual = ticketCalc(1,2);
diff = Math.abs(expected-actual);
if (diff < tolerance)
{
print('test 2 passed');
}
else
{
print('test 2 failed');
print('expected=' + expected);
print('actual=' + actual);
}
} // function testTicketCalc
js> load("ticketCalcStub.js");
js> load("testTicketCalc.js");
js> testTicketCalc()
test 1 failed
expected=125
actual=-42
test 2 failed
expected=160
actual=-42
js>
|
js> load("ticketCalc.js");
js> load("testTicketCalc.js");
js> testTicketCalc()
test 1 passed
test 2 passed
js> ticketCalc(0,1)
65
js> ticketCalc(1,0)
30
js> ticketCalc(2,0)
60
js> ticketCalc(0,2)
130
js> ticketCalc(1,2)
160
js> ticketCalc(2,1)
125
js> |