Meeting 11
Building Your Own Objects
11.1 Homework Discussion
Professor: Are we getting a little arithmetic practice today?
Mike: I don’t know. Our generator still nee ds some cosmetic touch-ups but I think it’s
working.
Professor: Don’t worry about that. Please, go on, show me what y ou’ve got.
Mike: This is our function tha t produce s a single equation:
/*
* Returns a randomly generated equation together with the solution.
* Parameters:
* oper: the desired operator in form of a string ("+", "-",
* "*", or "/")
* maxVal: the maximum allowed value for the two operands
* Returns:
* An array with two elements:
* -The generated equation as a string
* -The solution as a number
* Example:
* generateEquation("+", 10, 10) may return the array
* ["8+2=_____", 10]
*/
var generateEquation = function(oper, maxVal) {
var output = [];
var firstOper = Math.round(Math.random() * maxVal);
var secondOper = Math.round(Math.random() * maxVal);
var solution, tmp;
switch (oper) {
case "+":
solution = firstOper + secondOper;
break;
205
case "-":
if (firstOper < secondOper) {
//The difference shouldn’t be negative, so swap the operands.
tmp = firstOper;
firstOper = secondOper;
secondOper = tmp;
}
solution = firstOper - secondOper;
break;
case "*":
solution = firstOper * secondOper;
break;
case "/":
if (secondOper == 0) {
//Shouldn’t divide by zero.
secondOper++;
}
//Uses the product in place of the dividend, so the result is
//always an integer with no remainder.
tmp = firstOper * secondOper;
solution = firstOper;
firstOper = tmp;
}
output[0] = firstOper + oper;
output[0] += secondOper + "=_____";
output[1] = solution;
return output;
};
Professor: Very nice indeed! I like how you commented the function.
Maria: We found some recommendations about how to write comments for functio ns
on the Internet. We discovered that it is extremely useful to have our fun ctions com-
mented in this way, so we don’t have to wonder about how they work every time we
want to use them.
Professor: I don’t think the code needs any further explanation.
Mike: In the end we tested the function in the following man ner:
var i;
for (i = 0; i < 20; i++) {
document.write("<div>" + generateEquation("-", 10)[0] + "</div>");
}
Because the functio n returns an array, we used an array access operator directly on the
function call in orde r to extra ct equations and leave out the solutions. Here is how the
resulting worksheet looks.
206 Meeting 11. Building Your Own Objects
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.38.24