This might be really simple, so I do apologise but I can't find any other question asking the same/similar. Here goes...
I am trying to find a way to add up all the case values used in each switch. So to calculate all the days of the week numbers and output the total numbers in the following
const getSleepHours = (day) => {
switch(day) {
case "Monday":
return "8";
break;
case "Tuesday":
return "9";
break;
case "Wednesday":
return "9.5";
break;
case "Thursday":
return "11";
break;
case "Friday":
return "10.5";
break;
case "Saturday":
return "13";
break;
case "Sunday":
return "12";
break;
default:
return "Not sure what day that is";
}
};
So 8 + 9 + 9.5 + 11 + 10.5 + 13 + 12. So far I have tried things like the following
const getSleepHours = (day) => {
switch(day) {
case "Monday":
return "8";
break;
case "Tuesday":
return "9";
break;
case "Wednesday":
return "9.5";
break;
case "Thursday":
return "11";
break;
case "Friday":
return "10.5";
break;
case "Saturday":
return "13";
break;
case "Sunday":
return "12";
break;
default:
return "Not sure what day that is";
}
};
const getActualSleepHours = () => {
const getSleepHours = ("Monday","Sunday");
return getSleepHours();
};
console.log(getSleepHours());
You could get the value for each day of the week, parse it as a float number. Then use those values to calculate the total (for example by using reduce()).
Also if you return out of a case, you don't need to break because it is no longer reachable.
const getSleepHours = (day) => {
switch (day) {
case "Monday":
return "8";
case "Tuesday":
return "9";
case "Wednesday":
return "9.5";
case "Thursday":
return "11";
case "Friday":
return "10.5";
case "Saturday":
return "13";
case "Sunday":
return "12";
default:
return "Not sure what day that is";
}
};
const days = [
"Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday", "Sunday"
];
// get hours as float values
const sleepHours = days.map((d) => parseFloat(getSleepHours(d)));
// calculate the total
const sum = sleepHours.reduce((a, b) => a + b, 0);
console.log(sum);
You can do without switch-case
// 1️⃣
// Using Map object
// If you define duplicated key It won's so error
const sleepHours = new Map([
['monday', 8],
['tuesday', 9],
['wednesday', 9.5],
['thursday', 11],
['friday', 10.5],
['saturday', 13],
['sunday', 12],
])
let totalSleepHours = 0
for (const [key, value] of sleepHours) {
totalSleepHours += value
}
// 2️⃣
// Using object
const sleepHours = {
monday: 8,
tuesday: 9,
wednesday: 9.5,
thursday: 11,
friday: 10.5,
saturday: 13,
sunday: 12,
}
// If not provide initial value, array element at index 0 is used as the initial value
Object.values(sleepHours).reduce((acc, curr) => acc += curr)