Jump to content

Help with my Javascript Adventures

Energycore
Go to solution Solved by FezBoy,

The way switches.are evaluated is different to that of ifs.  You shouldn't have foo===bar in a case, you would do switch (Foo){case: bar}

 

This unfortunately make it difficult to check if something is positive, negative, or zero.  I think that an if else chain would be your best bet.

 

Scratch that, try this:

Quote

switch (Math.sign(sleepDebt)) {
    case 0:
      return('You got the perfect amount of sleep!');
    case 1:
      return('You should get some rest!');
    case -1:
      return('You got more sleep than needed!');
    default:
      return('Check your code dude!');
 }

Math.sign(foo) returns -1 for foo<0, 0 for foo===0, and 1 for foo>0.  The switch statement compares that to 0, -1, or 1 to determine which path to take.

 

(Please excuse mobile formatting)

 

See the MDN:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign

 

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch

So far I've really enjoyed learning Javascript. It's an awesome problem solving challenge where you need to pay great attention to detail.

 

However I ran into a bump and I'm not sure how to handle it.

 

I have this block of code as part of a project for a 'Sleep Debt Calculator':

 

Spoiler

// This first function serves only the purpose of storing daily sleep hours in a week.
const getSleepHours = day => {
  day = day.toLowerCase();
  switch (day) {
    case 'monday':
      return 8;
    case 'tuesday':
      return 7;
    case 'wednesday':
      return 6;
    case 'thursday':
      return 5;
    case 'friday':
      return 4;
    case 'saturday':
      return 3;
    case 'sunday':
      return 2;
    default:
      console.log('Error: Invalid Day')
  }
};
// These next two arrow functions are the ideal number of hours in a week (h in a day * 7) and the actual number of hours (sum of each day's hours)
const getActualSleepHours = () => (getSleepHours('monday') + getSleepHours('tuesday') + getSleepHours('wednesday') + getSleepHours('thursday') + getSleepHours('friday') + getSleepHours('saturday') + getSleepHours('sunday'));
const getIdealSleepHours = () => {
  const idealHours = 8;
  return idealHours * 7;
};
// This is where the meat and potatos are. This is where the problems begin, apparently.
const calculateSleepDebt = () => {
  let sleepDebt = (getIdealSleepHours() - getActualSleepHours());
  switch (sleepDebt) {
    case sleepDebt === 0:
      return('You got the perfect amount of sleep!');
    case sleepDebt > 0:
      return('You should get some rest!');
    case sleepDebt < 0:
      return('You got more sleep than needed!');
    default:
      return('Check your code dude!');
  }
};
console.log(getActualSleepHours());
console.log(getIdealSleepHours());
console.log(calculateSleepDebt());

 

Now as of right now, running the code will log the following into the console

35
56
Check your code dude!

Because the last string relates to the calculateSleepDebt variable, it seems as though the switch statement is evaluating on sleepDebt not being equal, greater or lower than zero. However if I change the block to this:

const calculateSleepDebt = () => {
  let sleepDebt = (getIdealSleepHours() - getActualSleepHours());
  console.log(sleepDebt) // This allows me to see the value of sleepDebt in the console
  switch (sleepDebt) {
    case sleepDebt === 0:
      return('You got the perfect amount of sleep!');
    case sleepDebt > 0:
      return('You should get some rest!');
    case sleepDebt < 0:
      return('You got more sleep than needed!');
    default:
      return('Check your code dude!');
  }
};

Then I can clearly see that the value of sleepDebt is 21, which is correct.

 

So there's gotta be something wrong with my switch statement, but I'm stumped. What did I write wrong, I wonder?

 

As always I really appreciate all your guys' help :)

 

EDIT: I was able to run the code just fine with a chain of if-else statements. However I'm interested in whether I can write this with a switch statement because a) it's less keystrokes and each keystroke counts when you're coding against the clock, and b) as a mathematician, case x = 0 / case x > 0 / case x < 0 is a very common, very intuitive notion that's used in a vast majority of math theories.

We have a NEW and GLORIOUSER-ER-ER PSU Tier List Now. (dammit @LukeSavenije stop coming up with new ones)

You can check out the old one that gave joy to so many across the land here

 

Computer having a hard time powering on? Troubleshoot it with this guide. (Currently looking for suggestions to update it into the context of <current year> and make it its own thread)

Computer Specs:

Spoiler

Mathresolvermajig: Intel Xeon E3 1240 (Sandy Bridge i7 equivalent)

Chillinmachine: Noctua NH-C14S
Framepainting-inator: EVGA GTX 1080 Ti SC2 Hybrid

Attachcorethingy: Gigabyte H61M-S2V-B3

Infoholdstick: Corsair 2x4GB DDR3 1333

Computerarmor: Silverstone RL06 "Lookalike"

Rememberdoogle: 1TB HDD + 120GB TR150 + 240 SSD Plus + 1TB MX500

AdditionalPylons: Phanteks AMP! 550W (based on Seasonic GX-550)

Letterpad: Rosewill Apollo 9100 (Cherry MX Red)

Buttonrodent: Razer Viper Mini + Huion H430P drawing Tablet

Auralnterface: Sennheiser HD 6xx

Liquidrectangles: LG 27UK850-W 4K HDR

 

Link to comment
Share on other sites

Link to post
Share on other sites

Three =-signs means check the value + type of variable. Perhaps the 0 you mention there is not a variable of the type of 'let', but perhaps an int by default?

Normally I would say "just hover over the 0 in your IDE and see what the variable type is", but I am not sure if there is an IDE for JS that supports this.

 

"We're all in this together, might as well be friends" Tom, Toonami.

 

mini eLiXiVy: my open source 65% mechanical PCB, a build log, PCB anatomy and discussing open source licenses: https://linustechtips.com/topic/1366493-elixivy-a-65-mechanical-keyboard-build-log-pcb-anatomy-and-how-i-open-sourced-this-project/

 

mini_cardboard: a 4% keyboard build log and how keyboards workhttps://linustechtips.com/topic/1328547-mini_cardboard-a-4-keyboard-build-log-and-how-keyboards-work/

Link to comment
Share on other sites

Link to post
Share on other sites

The way switches.are evaluated is different to that of ifs.  You shouldn't have foo===bar in a case, you would do switch (Foo){case: bar}

 

This unfortunately make it difficult to check if something is positive, negative, or zero.  I think that an if else chain would be your best bet.

 

Scratch that, try this:

Quote

switch (Math.sign(sleepDebt)) {
    case 0:
      return('You got the perfect amount of sleep!');
    case 1:
      return('You should get some rest!');
    case -1:
      return('You got more sleep than needed!');
    default:
      return('Check your code dude!');
 }

Math.sign(foo) returns -1 for foo<0, 0 for foo===0, and 1 for foo>0.  The switch statement compares that to 0, -1, or 1 to determine which path to take.

 

(Please excuse mobile formatting)

 

See the MDN:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign

 

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch

Edited by FezBoy
Further developments
Resident Mozilla Shill.   Typed on my Ortholinear JJ40 custom keyboard
               __     I am the ASCIIDino.
              / _)
     _.----._/ /      If you can see me you 
    /         /       must put me in your 
 __/ (  | (  |        signature for 24 hours.
/__.-'|_|--|_|        
Link to comment
Share on other sites

Link to post
Share on other sites

14 minutes ago, minibois said:

Three =-signs means check the value + type of variable. Perhaps the 0 you mention there is not a variable of the type of 'let', but perhaps an int by default?

Normally I would say "just hover over the 0 in your IDE and see what the variable type is", but I am not sure if there is an IDE for JS that supports this.

 

JavaScript is very loosely typed.  "let" is not a type, rather an alias for "var". Neither defines any type.

 

Note: var and let are NOT the same but are often treated as such.  Car declares global variables, whereas let is local.

 

Var: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var

Let: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

 

Scope: https://developer.mozilla.org/en-US/docs/Glossary/Scope

Type: https://developer.mozilla.org/en-US/docs/Glossary/Type

Resident Mozilla Shill.   Typed on my Ortholinear JJ40 custom keyboard
               __     I am the ASCIIDino.
              / _)
     _.----._/ /      If you can see me you 
    /         /       must put me in your 
 __/ (  | (  |        signature for 24 hours.
/__.-'|_|--|_|        
Link to comment
Share on other sites

Link to post
Share on other sites

4 minutes ago, FezBoy said:

JavaScript is very loosely typed.  "let" is not a type, rather an alias for "var". Neither defines any type.

 

Note: var and let are NOT the same but are often treated as such.  Car declares global variables, whereas let is local.

 

Var: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var

Let: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

 

Scope: https://developer.mozilla.org/en-US/docs/Glossary/Scope

Type: https://developer.mozilla.org/en-US/docs/Glossary/Type

The definition of === would be:

Quote

equal value and equal type

https://www.w3schools.com/jsref/jsref_operators.asp

 

What I was thinking, is that javascript is looking at 'let sleepDebt' contains the same as '0' (an int presumably), but it's a variable of a different type, thus would still return false.

But that was just a feeling, not something from experience I could mention.

"We're all in this together, might as well be friends" Tom, Toonami.

 

mini eLiXiVy: my open source 65% mechanical PCB, a build log, PCB anatomy and discussing open source licenses: https://linustechtips.com/topic/1366493-elixivy-a-65-mechanical-keyboard-build-log-pcb-anatomy-and-how-i-open-sourced-this-project/

 

mini_cardboard: a 4% keyboard build log and how keyboards workhttps://linustechtips.com/topic/1328547-mini_cardboard-a-4-keyboard-build-log-and-how-keyboards-work/

Link to comment
Share on other sites

Link to post
Share on other sites

Thank you guys. Programming feels like black magic when you're  just starting out lol.

We have a NEW and GLORIOUSER-ER-ER PSU Tier List Now. (dammit @LukeSavenije stop coming up with new ones)

You can check out the old one that gave joy to so many across the land here

 

Computer having a hard time powering on? Troubleshoot it with this guide. (Currently looking for suggestions to update it into the context of <current year> and make it its own thread)

Computer Specs:

Spoiler

Mathresolvermajig: Intel Xeon E3 1240 (Sandy Bridge i7 equivalent)

Chillinmachine: Noctua NH-C14S
Framepainting-inator: EVGA GTX 1080 Ti SC2 Hybrid

Attachcorethingy: Gigabyte H61M-S2V-B3

Infoholdstick: Corsair 2x4GB DDR3 1333

Computerarmor: Silverstone RL06 "Lookalike"

Rememberdoogle: 1TB HDD + 120GB TR150 + 240 SSD Plus + 1TB MX500

AdditionalPylons: Phanteks AMP! 550W (based on Seasonic GX-550)

Letterpad: Rosewill Apollo 9100 (Cherry MX Red)

Buttonrodent: Razer Viper Mini + Huion H430P drawing Tablet

Auralnterface: Sennheiser HD 6xx

Liquidrectangles: LG 27UK850-W 4K HDR

 

Link to comment
Share on other sites

Link to post
Share on other sites

22 hours ago, Energycore said:

Thank you guys. Programming feels like black magic when you're  just starting out lol.

It IS black magic I'm afraid but you learn to accept it ?


 

Link to comment
Share on other sites

Link to post
Share on other sites

1 hour ago, camjocotem said:

It IS black magic I'm afraid but you learn to accept it ?

No, it being black magic is good.

We have a NEW and GLORIOUSER-ER-ER PSU Tier List Now. (dammit @LukeSavenije stop coming up with new ones)

You can check out the old one that gave joy to so many across the land here

 

Computer having a hard time powering on? Troubleshoot it with this guide. (Currently looking for suggestions to update it into the context of <current year> and make it its own thread)

Computer Specs:

Spoiler

Mathresolvermajig: Intel Xeon E3 1240 (Sandy Bridge i7 equivalent)

Chillinmachine: Noctua NH-C14S
Framepainting-inator: EVGA GTX 1080 Ti SC2 Hybrid

Attachcorethingy: Gigabyte H61M-S2V-B3

Infoholdstick: Corsair 2x4GB DDR3 1333

Computerarmor: Silverstone RL06 "Lookalike"

Rememberdoogle: 1TB HDD + 120GB TR150 + 240 SSD Plus + 1TB MX500

AdditionalPylons: Phanteks AMP! 550W (based on Seasonic GX-550)

Letterpad: Rosewill Apollo 9100 (Cherry MX Red)

Buttonrodent: Razer Viper Mini + Huion H430P drawing Tablet

Auralnterface: Sennheiser HD 6xx

Liquidrectangles: LG 27UK850-W 4K HDR

 

Link to comment
Share on other sites

Link to post
Share on other sites

among other things , LET is block scoped, meaning its scope exists only between { }

 

var a = 1;
var b = 2;

if (a== 1) {

  let x = a + b;
  console.log(x);  // prints 3
 
}

console.log(x); // ReferenceError: x is not defined

use developer tools to see console.  the second console.log will give error or undefined because x only exists inside the if

also let will not allow you to recreate the variable, it will say it already exists and your code will fail.

you can't say let a = something; more than once in a block/function etc

 

 

Link to comment
Share on other sites

Link to post
Share on other sites

Just now, mariushm said:

among other things , LET is block scoped, meaning its scope exists only between { }

 


var a = 1;
var b = 2;

if (a== 1) {

  let x = a + b;
  console.log(x);  // prints 3
 
}

console.log(x); // ReferenceError: x is not defined

use developer tools to see console.  the second console.log will give error or undefined because x only exists inside the if

also let will not allow you to recreate the variable, it will say it already exists and your code will fail.

you can't say let a = something; more than once in a block/function etc

 

 

So I'm just starting the scope lesson tonight, and what you say makes sense. I'll remember to use let when I want a variable to only be usable inside a function.

 

Fun times!

We have a NEW and GLORIOUSER-ER-ER PSU Tier List Now. (dammit @LukeSavenije stop coming up with new ones)

You can check out the old one that gave joy to so many across the land here

 

Computer having a hard time powering on? Troubleshoot it with this guide. (Currently looking for suggestions to update it into the context of <current year> and make it its own thread)

Computer Specs:

Spoiler

Mathresolvermajig: Intel Xeon E3 1240 (Sandy Bridge i7 equivalent)

Chillinmachine: Noctua NH-C14S
Framepainting-inator: EVGA GTX 1080 Ti SC2 Hybrid

Attachcorethingy: Gigabyte H61M-S2V-B3

Infoholdstick: Corsair 2x4GB DDR3 1333

Computerarmor: Silverstone RL06 "Lookalike"

Rememberdoogle: 1TB HDD + 120GB TR150 + 240 SSD Plus + 1TB MX500

AdditionalPylons: Phanteks AMP! 550W (based on Seasonic GX-550)

Letterpad: Rosewill Apollo 9100 (Cherry MX Red)

Buttonrodent: Razer Viper Mini + Huion H430P drawing Tablet

Auralnterface: Sennheiser HD 6xx

Liquidrectangles: LG 27UK850-W 4K HDR

 

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×