Alternate Approaches

A typical question asked in "History of JavaScript" classes where the teacher mistakenly believes they are teaching programming.

Question:

Before your boss allows adjustable thermostats in the office suite, he must be convinced that major temperature variations occur in different offices and within each office on different days. You're to write a program that allows each employee to enter the temperature at noon on each of five days and displays the highest, lowest, and average (mean) temperatures.

Using pseudocode, design a complete algorithm that accepts five daily temperature readings and displays the highest, lowest, and average (mean) temperatures. Use a For loop to take the five readings. (Hint: Initialize the highest and lowest temperature variable to the first temperature that's read, and then compare other temperatures to see whether they're lower or higher.)

JavaScript Answer 1:

var temperature = function() {
this.temps = [];
};
temperature.prototype.read = function(n) {
if (n != +n) return false;
this.temps.push(+n);
return true;
};
temperature.prototype.high = function() {
return Math.max.apply(null, this.temps);
};
temperature.prototype.low = function() {
return Math.min.apply(null, this.temps);
};
temperature.prototype.ave = function() {
return this.temps.reduce(function(a, b) {return a+b;})/this.temps.length;
};
 
var t = new temperature();
for (var i=0; i < 5; ) {
if (t.read(prompt("Please enter the temperature reading."))) i++;
}
console.log("The highest number is " + t.high());
console.log("The lowest number is " + t.low());
console.log("The average of the temperatures is " + t.ave());

Now the actual question in this case asked for the student to first write pseudo-code and then translate it into JavaScript and this solution doesn't work with that requirement since you can't write pseudo-code for objects - particularly ones where each method basically contains a single statement. You can't write pseudo-code for event driven processing either and so pseudo-code is just about and always has been irrelevant to JavaScript but then that just demonstrates how little a teacher asking for it knows about real JavaScript.

Note though that we have taken into account the irrelevant criteria of using a for loop to collect the values (for testing our temperature object only - that part would be discarded if the temperature object were to be used in the real world). We have however ignored the hint to initialize the unnecessary variables that the question mistakenly believes are needed.

JavaScript Answer 2:

Now let's forget all the extraneous requirements from the problem and do it properly in JavaScript. To start with instead of a loop we need a form to read in the five values. We can use the following as the basis for the HTML (prettied up however you like):

<form>
<input type="text" class="temp">
<input type="text" class="temp">
<input type="text" class="temp">
<input type="text" class="temp">
<input type="text" class="temp">
<input type="button" id="go" value="go">
</form>
<p id="answer"></p>

We will also ignore the object we created above and simply create the simplest JavaScript that we can that will produce the desired results. Note how nearly half the script is actually the messages to be output at the end as the calculations are so trivial that the code can be built right into the messages themselves.

function results() {
var temps = [];
[].forEach.call(document.querySelectorAll('.temp'), function(el) {
temps.push(+el.value); });
document.getElementById('answer').innerHTML =
["The highest number is "+Math.max.apply(null, temps),
"The lowest number is "+Math.min.apply(null, temps),
"The average of the temperatures is "+
temps.reduce(function(a, b) {return a+b;})/temps.length
].join('<br>');
}
function validate() {
if (this != +this) {
document.getElementById('answer').innerHTML = 'Please enter a number';
this.focus();
}
}
 
document.getElementById('go').addEventListener('click',results,false);
[].forEach.call(document.querySelectorAll('.temp'), function(el) {
el.addEventListener('blur',validate,false);
});

Note that we have set up validation to produce an error message if something that isn't a number is entered into any of the fields but an empty field will simply be considered to be zero. We could add more code to check for this if it were necessary.

 

This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow
Donate