I am trying to write conditional statements for a large data set in JavaScript. The goal is to calculate Calorie (results) intake based on age and lifestyle.
Here is an example:
HTML
<label>Enter Age (2 to 100)</label>
<input id="getAge" type="text" placeholder="" />
<label>Enter 1 for Sedentary, 2 for Moderate, 3 for Active</label>
<input id="getLifeStyle" type="text" placeholder="" />
JavaScript:
let age, lifestyle, calorie;
age = document.getElementById("getAge").value
lifestyle = document.getElementById("getLifeStyle").value
// two
if (age==2) {
if (lifestyle==1) {
calorie=1000
}
if (lifestyle==2) {
calorie=2000
}
....
// three
else if (age==3) {
if (lifestyle==1) {
calorie=1000
}
if (lifestyle==2) {
calorie=2000
}....
// four...and so, until 100
// Show calorie
console.log("Calorie: " calorie)
Here is what I am trying to achieve:
Basically repeat the above several times. I am not an expert in JavaScript. While the above is working fine to get the results, I don't think this may be the most efficient way to write if-then-else. Are there any other efficient options in JavaScript to do this?
CodePudding user response:
A nested object indexed by age, then indexed by lifestyle would work.
const calorieData = {
2: {
1: 1000,
2: 2000,
},
3: {
1: 1000,
2: 2000,
}
};
// ...
const calories = calorieData[age][lifestyle];
A DRY-er version would use arrays instead, but it could require slightly more confusing code due to 0-based indicies.
const calorieData = [
// omit index 0
,
// omit index 1
,
[1000, 2000],
[1000, 2000],
// ...
];
// ...
// because lifestyle is 1-indexed
const calories = calorieData[age][lifestyle - 1];
CodePudding user response:
const LIFE_STYLE = {
SEDENTARY: '1',
MODERATE: '2',
ACTIVE: '3'
}
const data = [
{ age: 2, lifeStyle: LIFE_STYLE.SEDENTARY, calories: 1000 },
{ age: 3, lifeStyle: LIFE_STYLE.SEDENTARY, calories: 1000 }
]
const getCaloryData = (age, lifestyle) => {
const entry = data.find(entry => entry.age === age && entry.lifeStyle === lifestyle)
return entry ? entry.calories : undefined;
}
The complexity is higher but the readability is better.
CodePudding user response:
the best & shortest alternative way for that is using ternary operator