Simplify Nested If Else Statement In Javascript
I'm currently doing a body mass index calculation using html css and javascipt (using jquery library). In javascript or other programming language, how can I simplify multiple nest
Solution 1:
It can be simplified quite a bit if you supply a nested array with the "decision points":
functionbmi(age,b) {
const text=["underweight","healthy","overweight","obese","obese II","obese III"],
o={9:[14, 18.6, 21 ],
10:[14.2, 19.4, 22.2 ],
11:[14.6, 20.2, 23.2 ],
12:[15, 21, 24.2 ],
13:[15.4, 21.8, 25.2 ],
14:[16, 22.6, 26 ],
15:[16.6, 23.4, 26.8 ],
16:[17.2, 24.2, 27.6 ],
17:[17.8, 24.8, 28.2 ],
18:[18.5, 25, 30, 35, 40]};
let sc=o[Math.min(age,18)];
if (!sc) return"too young for BMI";
let i=sc.findIndex(v=>v>b);
if (i==-1) i=sc.lengthreturn text[i]
}
const tests=[[8,18],[12,23],[13,25],[14,26],[15,27],[16,16],[17,22],[22,42]];
tests.forEach(([age,b])=>console.log(age+"y, bmi="+b+" : "+bmi(age,b)))
Solution 2:
A way to simplify/beautify if
statements is to use switch
statements
For javascript: https://www.w3schools.com/js/js_switch.asp
Post a Comment for "Simplify Nested If Else Statement In Javascript"