Someone's JavaScript Homework
I decided to do someone's javascript homework
Isn't that cheating?
Nah. Here's the story. Someone listed code requirements at another website, and I came up with a solution. I didn't tell them about it, which means they'll probably never see this anyway. So that doesn't make me a cheater, that makes me a jerk.
The Assignment
Refer to the thread at webdeveloper.com.
Write a program to read in rainfall amounts for some number of days from a single text box (use split to separate out the values). It then finds and displays the average rainfall and the number of days that had more than the average rainfall.
CAUTION: You cannot assume that the values are always typed in with one blank between them and no leading or trailing blanks. You need to allow blanks everywhere (NaN test).
Let it rain
About the solution
The basic steps:
- Split the string into an array.
- Loop to eliminate (compress) all but numbers in the array.
- Loop to average the array.
- Loop to count the number of days over the average.
I decided to put the compress and average code into prototypes. It makes it less efficient, because those steps could've been done in one loop, but each of those prototypes could be reused outside of this project. Here is the prototype code:
Array.prototype.compressJustNumbers = function() { for (var i=this.length-1; i>= 0; i--) { if (isNaN(this[i]) || this[i].replace(/\s+/, '') == '') { this.splice(i, 1); } } } Array.prototype.getAverage = function() { var total = 0.0; for (var i=0; i<this.length; i++) { total += parseFloat(this[i]); } return total / this.length; }
isNaN
I'm not sure why the homework instructions say blanks should be tested with "NaN", because isNaN returns false for empty space or multiple spaces. In other words, it says that empty space is a number. To account for that, my compressJustNumbers prototype function does both an isNaN test and a test for empty quotes or all spaces.