Skip to content

Instantly share code, notes, and snippets.

@nax3t
Created August 1, 2021 20:19
Show Gist options
  • Save nax3t/eecb6465e1ea716f66732a8dbb5697f0 to your computer and use it in GitHub Desktop.
Save nax3t/eecb6465e1ea716f66732a8dbb5697f0 to your computer and use it in GitHub Desktop.
Guessing Game Refactor
let maximum = parseInt(prompt("Enter the maximum number!"));
while (!maximum) {
maximum = parseInt(prompt("Enter a valid number!"));
}
const targetNum = Math.floor(Math.random() * maximum) + 1;
let guess = parseInt(prompt("Enter your first guess!"));
let attempts = 1;
while (parseInt(guess) !== targetNum) {
if (guess === 'q') break;
attempts++;
if (guess > targetNum) {
guess = prompt("Too high! Enter a new guess:");
} else {
guess = prompt("Too low! Enter a new guess:");
}
}
if (guess === 'q') {
console.log("OK, YOU QUIT!");
} else {
console.log("CONGRATS YOU WIN!");
console.log(`You got it! It took you ${attempts} guesses`);
}
let maximum = parseInt(prompt("Enter the maximum number!"));
while (!maximum) {
maximum = parseInt(prompt("Enter a valid number!"));
}
const targetNum = Math.floor(Math.random() * maximum) + 1;
let guess = prompt("Enter your first guess!");
let attempts = 1;
while (parseInt(guess) !== targetNum) {
if (guess === 'q') break;
attempts++;
if (guess > targetNum) {
guess = prompt("Too high! Enter a new guess:");
} else if (guess < targetNum) {
guess = prompt("Too low! Enter a new guess:");
} else {
guess = prompt(`Your guess is ${guess}, which is not higher or lower, please guess a number value:`);
}
}
if (guess === 'q') {
console.log("OK, YOU QUIT!");
} else {
console.log("CONGRATS YOU WIN!");
console.log(`You got it! It took you ${attempts} guesses`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment