JSFiddle - React, Tailwind, and code Playground
by mschock
JavaScript
// temperature-tracker
function TempTracker() {
this.temps = [];
}
TempTracker.prototype.insert = function(temp) { // records a new temperature
this.temps.push(temp);
}
TempTracker.prototype.getMax = function() { // returns the highest temp we've seen so far
var highest = this.temps[0];
for (var i = 1; i < this.temps.length; i++) {
if (this.temps[i] > highest) {
highest = this.temps[i];
}
}
return highest;
}
TempTracker.prototype.getMin = function() { // returns the lowest temp we've seen so far
var lowest = this.temps[0];
for (var i = 1; i < this.temps.length; i++) {
if (this.temps[i] < highest) {
lowest = this.temps[i];
}
}
return lowest;
}
TempTracker.prototype.getMean = function() { // returns the mean of all temps we've seen so far
var sum = 0;
for (var i = 0; i < this.temps.length; i++) {
sum += this.temps[i];
}
return sum / this.temps.length;
}
TempTracker.prototype.getMode = function() { // returns the mode of all temps we've seen so far
var counts = {};
for (var i = 0; i < this.temps.length; i++) {
var temp = this.temps[i];
if (counts[temp]) {
counts[temp] += 1;
} else {
counts[temp] = 1;
}
}
var mode;
for (var key in counts) {
if (mode === undefined || counts[key] > mode) {
mode = key;
}
}
return mode;
}