Dozens of donuts

Another improvement to the Donut Manager we have wrote is about accepting donuts by dozens. Besides, we check also that the user won't input negative numbers as order.

To do that we will use the indexOf() method for a string, that returns the index where starts the specified substring in the current string. If there is no such a substring, -1 is returned.

We want to write a parseDonuts() JavaScript custom function that we would call in the update() to extract the number of donuts as input by the user, in this way:

var cDonuts = parseDonuts(document.getElementById("cdonuts"));
var gDonuts = parseDonuts(document.getElementById("gdonuts"));

If we have a "bad" value in the element, we reset the text to empty string. If we find "dozen" in the text we multiply the value by 12, and we write the actual value in the text:

function parseDonuts(text) {
var nrDonuts = parseInt(text.value);
if(isNaN(nrDonuts) || nrDonuts < 1) {
text.value = "";
return 0;
}
else if(text.value.indexOf("dozen") != -1) {
nrDonuts *= 12;
text.value = nrDonuts;
}
return nrDonuts;
}


Post written while reading chapter two of Head First JavaScript, a good book if you know nothing about JavaScript and not much about programming.

No comments:

Post a Comment