The calculateWeight()
exercise can be solved without the use of switch
or if/else if
blocks.
For example, the following solution using ternary operatorsâŚ
function calculateWeight(earthWeight, planet) {
// Perform validation first:
if (
Number.isNaN(earthWeight) ||
typeof earthWeight !== 'number' ||
typeof planet !== 'string'
)
return 'Invalid Argument. Provide valid Earth-weight(number) and Planet(string).';
const validPlanets = ['Mercury', 'Venus', 'Mars', 'Jupiter', 'Saturn'];
if (!validPlanets.includes(planet))
return 'Invalid Planet Entry. Try: Mercury, Venus, Mars, Jupiter, or Saturn.';
const g = planet === 'Mercury' ? 0.378
: planet === 'Venus' ? 0.907
: planet === 'Mars' ? 0.377
: planet === 'Jupiter' ? 2.36
: 0.916;
return earthWeight * g;
}
âŚwill yield the same results as this implementation (using switch
):
function calculateWeight(earthWeight, planet) {
if (
Number.isNaN(earthWeight) ||
typeof earthWeight !== 'number' ||
typeof planet !== 'string'
)
return 'Invalid Argument. Provide valid Earth-weight(number) and Planet(string).';
const validPlanets = ['Mercury', 'Venus', 'Mars', 'Jupiter', 'Saturn'];
if (!validPlanets.includes(planet))
return 'Invalid Planet Entry. Try: Mercury, Venus, Mars, Jupiter, or Saturn.';
let g;
switch (planet) {
case 'Mercury':
g = 0.378;
break;
case 'Venus':
g = 0.907;
break;
case 'Mars':
g = 0.377;
break;
case 'Jupiter':
g = 2.36;
break;
default:
g = 0.916;
}
return earthWeight * g;
}
âŚand this solution (using if/else if
):
function calculateWeight(earthWeight, planet) {
if (
Number.isNaN(earthWeight) ||
typeof earthWeight !== 'number' ||
typeof planet !== 'string'
)
return 'Invalid Argument. Provide valid Earth-weight(number) and Planet(string).';
const validPlanets = ['Mercury', 'Venus', 'Mars', 'Jupiter', 'Saturn'];
if (!validPlanets.includes(planet))
return 'Invalid Planet Entry. Try: Mercury, Venus, Mars, Jupiter, or Saturn.';
let g;
if (planet === 'Mercury') {
g = 0.378;
} else if (planet === 'Venus') {
g = 0.907;
} else if (planet === 'Mars') {
g = 0.377;
} else if (planet === 'Jupiter') {
g = 2.36;
} else {
g = 0.916;
}
return earthWeight * g;
}