Get Programming with JavaScript - Listing 12.04
Listing 12.04 - Guess the random number
var getGuesser = function () {
var secret = Math.floor(Math.random() * 10 + 1);
return function (userNumber) {
if (userNumber === secret) {
return "Well done!";
} else {
return "Unlucky, try again.";
}
};
};
var guess = getGuesser();
Further Adventures
Listing 12.04 - Guess the random number - Task 3
- Change the code so the secret number is between 30 and 50.
var getGuesser = function () {
var secret = Math.floor(Math.random() * 21 + 30);
return function (userNumber) {
if (userNumber === secret) {
return "Well done!";
} else {
return "Unlucky, try again.";
}
};
};
var guess = getGuesser();
Listing 12.04 - Guess the random number - Task 5
- Create a function called 'between' that returns a random whole number between two numbers passed as arguments.
var between = function (num1, num2) {
var lower = Math.min(num1, num2);
var upper = Math.max(num1, num2);
var range = upper - lower + 1;
return Math.floor(Math.random() * range + lower);
};
between(8, 12) gives lower = 8, upper = 12, range = 5. Note there are 5 possible whole numbers between 8 and 12: 8, 9, 10, 11 and 12.