Help refactoring (Sleep Debt Calc)

Hi,
I wanted to slim down and refactor this code from the Sleep Debt Calculator project. I have the answer but I wanted to see if I could do better.
Sleep Debt Calculator Project

CODE

const getSleepHours = (day) => {
  if (day === "monday") {
    return 8;
  } else if (day === "tuesday") {
    return 8;
  } else if (day === "wednesday") {
    return 8;
  } else if (day === "thursday") {
    return 8;
  } else if (day === "friday") {
    return 8;
  } else if (day === "saturday") {
    return 10;
  } else if (day === "sunday") {
    return 11;
  } else {
    return "Please pick a day of the week";
  }
};

REFACTOR

const getSleepHours = (day) => {
  if (day === 'monday' || 'tuesday' || 'wednesday' || 'thursday' || 'friday') {
    return 8
  } else if (day === 'saturday') {
    return 10
  } else if (day === 'sunday') {
    return 11
  } else {
    return "Please pick any day of the week"
  }
}

console.log gives me

console.log(getSleepHours('monday'))
console.log(getSleepHours('friday'))
console.log(getSleepHours('saturday'))
console.log(getSleepHours('sunday'))
console.log(getSleepHours('January'))

8
8
8
8
8

Why does the refactor not work?. :nerd_face:

day === 'monday' || 'tuesday' || 'wednesday' || 'thursday' || 'friday'

here you just evaluate the first part
saying if (x === y || 'anystring') will always evaluate to true because non-null non-undefined values evaluate to true. You have to be explicit if (x === y || x === 'anystring').

So like

day === 'monday' || day === 'tuesday' || ...

That’s right. When it comes time for the compiler or interpreter to parse these if statements, it has no way of knowing your intentions. The rare case is that you would chain them like in speech, the common case is that you might have if (y || z || t), if any of these are true, evaluate to true. But you cannot do if (y || z || t) if you automatically interpret if (x ===y || z || t) to mean if (x ===y || x===z || x===t) by default (they are intrinsically different statements).

So the choice for the compiler/interpreter is going to err on the side of the more common case. /tangent In fact I don’t know how you might be able to cleanly decouple if statements for implicit chaining. You might have to introduce some extra syntax but that seems more troublesome in the end. Maybe something like (x==y || ...z || ...t) :thinking: /endTangent

There are of course switch statements, and some languages offer nice pattern matching (elixir, rust, etc.)

1 Like