JSFiddle - React, Tailwind, and code Playground
Temperature tracker
by Varayut Lerdkanlayanawat
JavaScript
// https://www.interviewcake.com/question/javascript/temperature-tracker
class TempTracker {
constructor() {
this.max = -Infinity;
this.min = Infinity;
// Keep track of mean
this.mean = 0;
this.totalSum = 0;
this.totalNumbers = 0;
// Keep track of mode
this.occurrences = new Map();
this.maxOccurrence = 0;
this.mode = 0;
}
getMin() {
return this.min;
}
getMax() {
return this.max;
}
getMean() {
return this.mean;
}
getMode() {
return this.mode;
}
insert(val) {
if (max < val) this.max = val;
if (min > val) this.min = val;
// Mean
this.totalNumbers += 1;
this.totalSum += val;
this.mean = this.totalSum / this.totalNumbers;
// Mode
if (this.occurrences.has(val)) {
this.occurrences.set(val, 1);
} else {
this.occurrences.set(val, this.occurrences.get(val) + 1);
}
if (this.occurrences.get(val) > this.maxOccurrence) {
this.mode = val;
this.maxOccurrence = this.occurrences.get(val);
}
}
}