Skip to content

Instantly share code, notes, and snippets.

@pomomi
Last active January 16, 2022 16:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pomomi/3122615a941e1aa89e4d47f2160b2d97 to your computer and use it in GitHub Desktop.
Save pomomi/3122615a941e1aa89e4d47f2160b2d97 to your computer and use it in GitHub Desktop.
Challenge Project: Number Guesser (codeacademy)
let humanScore = 0;
let computerScore = 0;
let currentRoundNumber = 1;
// Write your code below:
function generateTarget() {
return Math.floor(Math.random() * 9);
};
function compareGuesses(human,comp,secret) {
let humanGuess = Math.abs(human - secret);
let compGuess = Math.abs(comp - secret);
// make more compact? like:
return (humanGuess <= compGuess) ? true : false;
};
function updateScore(winner) {
switch (winner) {
case ('human'):
humanScore += 1;
break;
case ('computer'):
computerScore += 1;
break;
default:
'error'
break;
}
};
function advanceRound() {
currentRoundNumber += 1;
};
@Allen-Valdez
Copy link

Allen-Valdez commented Jan 16, 2022

Hey Pomomi! Great job on finishing the project. I am here because you said if there is any way we can refactor your code and there is! For your functions generateTarget() and advanceRound() you can make them one liners! How?
Below will be an example for your generateTarget() function. The same principle can be applied to your advanceRound() function and also you can use the increment operator to add 1 to currentRoundNumber to make it look nicer!
const generateTarget = () => Math.floor(Math.random() * 9);
Now you are wondering what the heck did I do! Well, let me break it down.

I changed your function into an arrow function (ES6 syntax) which is typically written as:
const functionName = (parameter) => {
Some code here
Maybe some more code here
}
BUT if you recall the lesson they stated if you are returning ONE LINE you can skip the figure brackets (or curly braces which are these -> {} ) and just write what you want to return. Like this:
const functionName = (parameter) => codeWeWantToReturnHere
In this instance, we want to return Math.floor(Math.random() * 9) so we can just write it the way I did. If you want to learn more about this, go back to Learn JavaScript Syntax: Functions Calling a function. You will see a lesson called Concise Body Arrow Functions on page 10!

@pomomi
Copy link
Author

pomomi commented Jan 16, 2022

@Allen-Valdez A single line would definitely look a lot nicer! Thank you so much for taking the time to write such a wonderfully detailed comment. I really appreciate the help!

@Allen-Valdez
Copy link

@pomomi Yeah no problem! If you have any questions please feel free to reach out!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment