In a class I have a function condition() with an if statement that calls other functions and I'm trying to convert to Object Literal. It would be possible?
LOW_HUMIDITY = 20;
HIGH_TEMP = 40;
LOW_TEMP = 5;
class Country {
constructor(temperature, humidity) {
this.temperature = temperature;
this.humidity = humidity;
}
condition() {
if (this.humidity < LOW_HUMIDITY) {
return new fooFunction1();
}
if (this.temperature > HIGH_TEMP) {
return new fooFunction2();
}
if (
(this.temperature > LOW_TEMP) &
(this.temperature < HIGH_TEMP) &
(this.humidity > LOW_HUMIDITY)
) {
return new fooFunction3();
}
if (this.temperature < LOW_TEMP) {
return new fooFunction4();
}
return new fooFunction5();
}
}
I managed to get the same behavior by switching to switch case, but I couldn't pass Object Literal.
condition() {
switch (true) {
case this.humidity < LOW_HUMIDITY:
return new fooFunction1();
case this.temp > HIGH_TEMP:
return new new fooFunction2();
case this.temp < LOW_TEMP:
return new fooFunction3();
case (this.temp > LOW_TEMP):
case (this.temp < HIGH_TEMP):
case (this.humidity > LOW_HUMIDITY):
return new fooFunction4();
default:
fooFunction5();
}
}
Because the examples I found about this conversion use if else and receive a parameter for comparison. Example:
function getTranslation(rhyme) {
if (rhyme.toLowerCase() === "apples and pears") {
return "Stairs";
} else if (rhyme.toLowerCase() === "hampstead heath") {
return "Teeth";
} else if (rhyme.toLowerCase() === "loaf of bread") {
return "Head";
} else if (rhyme.toLowerCase() === "pork pies") {
return "Lies";
} else if (rhyme.toLowerCase() === "whistle and flute") {
return "Suit";
}
return "Rhyme not found";
}
It's converted to Object Literal which didn't make me clear how I can use it in my condition function:
function getTranslationMap(rhyme) {
const rhymes = {
"apples and pears": "Stairs",
"hampstead heath": "Teeth",
"loaf of bread": "Head",
"pork pies": "Lies",
"whistle and flute": "Suit",
};
return rhymes[rhyme.toLowerCase()] ?? "Rhyme not found";
}