Question about Sleep Debt Calculator

In the Sleep Debt Calculator (https://www.codecademy.com/courses/introduction-to-javascript/projects/sleep-debt-calculator) exercise, I have a question about defining a function based on my switch statement:

const getSleepHours = day =>{
switch(day){
case ‘monday’: return 8
break;
case ‘tuesday’: return 8
break;
case ‘wednesday’: return 8
break;
case ‘thursday’ : return 8
break;
case ‘friday’ : return 8
break;
case ‘saturday’ : return 8
break;
case ‘sunday’ : return 8
break;
}
}

that is the switch statement, but what I want to know is why when I call this function:

const getActualSleepHours = () => getSleepHours(‘monday’) + getSleepHours(‘tuesday’) + getSleepHours(‘wednesday’) + getSleepHours(‘thursday’) + getSleepHours(‘friday’) + getSleepHours(‘saturday’) +getSleepHours(‘sunday’) ;

it prints the total to the console, but when I code the function like this:

const getActualSleepHours = () => getSleepHours(‘monday’ + ‘tuesday’ + ‘wednesday’ + ‘thursday’ + ‘friday’ + ‘saturday’ + ‘sunday’);

it prints as undefined?

is there a way I can use the second function by changing something in my switch statement? it seems like it should work as it’s basically a condensed version of the first

1 Like

Your function acts on one day.
There’s no way it’ll magically act on multiple days - not unless you change its behaviour ie. insert a loop in it.
Concatenating strings won’t help you, no day is named 'mondaytuesdaywednesday ...'

I’d do either:

  • let getSleepHours have a variable number of arguments
  • but I’d rather call it multiple times, like so:
['monday', 'tuesday'].map(getSleepHours)

I find it is usually easier to solve the smallest scenario possible (one day) and then scaling it up with other functions (map)

// prints 24
console.log(
  ['tuesday', 'friday', 'monday']
    .map(getSleepHours)
    .reduce((a, b) => a + b)
)

I’d be pretty quick to replace the rather cumbersome switch with a lookup table along the lines of:

{ monday: 8
, tuesday: 100
, ...
}

Also, your break statements are unreachable because they come after return statements…

const getSleepHours = day => {
  switch (day) {
    case 'monday':    return 8
    case 'tuesday':   return 8
    case 'wednesday': return 8
    case 'thursday':  return 8
    case 'friday':    return 8
    case 'saturday':  return 8
    case 'sunday':    return 8
    default: picnic
  }
}
2 Likes