Estoy tratando de escribir declaraciones condicionales para un gran conjunto de datos en JavaScript. El objetivo es calcular la ingesta de calorías (resultados) en función de la edad y el estilo de vida.
Aquí hay un ejemplo:
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)Esto es lo que estoy tratando de lograr:
Básicamente repite lo anterior varias veces. No soy un experto en JavaScript. Si bien lo anterior funciona bien para obtener los resultados, no creo que esta sea la forma más eficiente de escribir if-then-else. ¿Hay otras opciones eficientes en JavaScript para hacer esto?
Un objeto anidado indexado por edad, luego indexado por estilo de vida funcionaría.
const calorieData = { 2: { 1: 1000, 2: 2000, }, 3: { 1: 1000, 2: 2000, } }; // ... const calories = calorieData[age][lifestyle];Una versión DRY-er usaría arreglos en su lugar, pero podría requerir un código un poco más confuso debido a los índices basados en 0.
const calorieData = [ // omit index 0 , // omit index 1 , [1000, 2000], [1000, 2000], // ... ]; // ... // because lifestyle is 1-indexed const calories = calorieData[age][lifestyle - 1];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; }La complejidad es mayor pero la legibilidad es mejor.
la forma alternativa mejor y más corta para eso es usar el operador ternario 👇
// two {age == 2 && lifestyle == 1 && calorie = 1000} {age == 2 && lifestyle == 2 && calorie = 2000} //three {age == 3 && lifestyle == 1 && calorie = 1000} {age == 3 && lifestyle == 2 && calorie = 2000} // until 100