81 lines
2.2 KiB
JavaScript

// PROBLEM
// We work for a company building a smart home thermometer.
// Out most recent task is this: "Given an array of temperatures"
// of one day, calculate the temperature amplitude. Keep in mind that somethimes
// there might be a sensor error"
const temperatures = [-3, -2, -6, -1, "error", 9, 13, 17, 15, 14, 9, 5];
const temperatures_doubled = [-3, -2, -6, -1, "error", 9, 13, 17, 15, 14, 9, 5];
// 1) Understanding the problem
// - What is temperature amplitude? Answer: Difference between highest and lowest temperature
// - How to compute max and min temperatures?
// - What's a sensor error? And what to do?
// 2) Breaking up into sub-problems
// - How to ignore errors?
// - Find max value in the array?
// - Find min value in the array?
// - Subtract min from max (amplitude) and return it
const getMinTemp = function (temps) {
let minTemp = temps[0];
for (let i = 0; i < temps.length; i++) {
const currTemp = temps[i];
if (currTemp < minTemp) minTemp = currTemp;
}
return minTemp;
};
const getMaxTemp = function (temps) {
let maxTemp = temps[0];
for (let i = 0; i < temps.length; i++) {
const currTemp = temps[i];
if (currTemp > maxTemp) maxTemp = currTemp;
}
return maxTemp;
};
const getOnlyNumbers = function (temps) {
let arrayOfNumbers = [];
for (let i = 0; i < temps.length; i++) {
const currTemp = temps[i];
if (typeof currTemp === "number") {
arrayOfNumbers.push(currTemp);
}
}
return arrayOfNumbers;
};
const getAmplitude = function (temps) {
const arrayOfTempsOnlyNumbers = getOnlyNumbers(temps);
const maxTemp = getMaxTemp(arrayOfTempsOnlyNumbers);
const minTemp = getMinTemp(arrayOfTempsOnlyNumbers);
return Math.abs(minTemp) + maxTemp;
};
console.log(getAmplitude(temperatures));
// PROBLEM 2
// Function should now receive 2 arrays of temps
// 1) Understanding the problem
// - With 2 arrays, should we implement functionality twice?
// NO! Just merge two arrays
// 2) Breaking up into sub-problems
// - Merge 2 arrays
const mergeArray = (temps1, temps2) => {
const mergedArray = temps1;
for (let i = 0; i < temps2.length; i++) {
mergedArray.push(temps2[i]);
}
return mergedArray;
};
const mergedArray = mergeArray(temperatures, temperatures_doubled);
console.log(mergedArray);