Consider the following task:
We have a list of average daily temperatures in different European cities.
{ Hamburg: [14, 15, 16, 14, 18, 17, 20, 11, 21, 18, 19,11 ],
Munich: [16, 17, 19, 20, 21, 23, 22, 21, 20, 19, 24, 23],
Madrid: [24, 23, 20, 24, 24, 23, 21, 22, 24, 20, 24, 22],
Stockholm: [16, 14, 12, 15, 13, 14, 14, 12, 11, 14, 15, 14],
Warsaw: [17, 15, 16, 18, 20, 20, 21, 18, 19, 18, 17, 20] }
We want to sort these cities into two groups: “warm” and “hot”. “warm” should be cities that have at least 3 days with temperatures above 19. “hot” should be cities where the temperature is more than 19 every day.
What I did in the end:
const _ = require('lodash');
let cities = {
Hamburg: [14, 15, 16, 14, 18, 17, 20, 11, 21, 18, 19,11 ],
Munich: [16, 17, 19, 20, 21, 23, 22, 21, 20, 19, 24, 23],
Madrid: [24, 23, 20, 24, 24, 23, 21, 22, 24, 20, 24, 22],
Stockholm: [16, 14, 12, 15, 13, 14, 14, 12, 11, 14, 15, 14],
Warsaw: [17, 15, 16, 18, 20, 20, 21, 18, 19, 18, 17, 20]
};
let isHot = (degrees) => {
return degrees > 19;
};
function getMinCategories(cities) {
let res = {
hot: [],
warm: []
};
_.forEach(cities, function(val,key) {
if(_.every(val, isHot)){
res.hot.push(key);
} else if(_.sumBy(val, degree => isHot(degree) ? 1 : 0) > 2){
res.warm.push(key);
}
});
return res;
}
console.log(getMinCategories(cities));
Is there a more elegant way to check "at least 3 days with a temperature> 19" instead of using the function _.sumBy? Perhaps using _.some()?