Get Programming with JavaScript - Listing 12.06
Listing 12.06 - A neater else-if block
JS Bin
var getGuesser = function () {
var secret = Math.floor(Math.random() * 10 + 1);
return function (userNumber) {
if (userNumber === secret) {
return "Well done!";
} else if (userNumber > secret) {
return "Too high!";
} else {
return "Too low!";
}
};
};
var guess = getGuesser();
Further Adventures
Listing 12.06 - A neater else-if block - Tasks 1 to 3
- Add a 'range' parameter to the function definition of getGuesser.
- Change the 10 after Math.random() to 'range'.
- Include an argument when getGuesser is called.
var getGuesser = function (range) {
var secret = Math.floor(Math.random() * range + 1);
return function (userNumber) {
if (userNumber === secret) {
return "Well done!";
} else if (userNumber > secret) {
return "Too high!";
} else {
return "Too low!";
}
};
};
var guess = getGuesser(20);
Listing 12.06 - A neater else-if block - Task 5
- Now add a second parameter, 'offset' and update the code to choose random numbers greater than or equal to the value of offset.
var getGuesser = function (range, offset) {
var secret = Math.floor(Math.random() * range + offset);
return function (userNumber) {
if (userNumber === secret) {
return "Well done!";
} else if (userNumber > secret) {
return "Too high!";
} else {
return "Too low!";
}
};
};
// 20 possible numbers starting at 10.
// i.e. from 10 to 29 inclusive
var guess = getGuesser(20, 10);