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