11.4. Receiving Function Arguments
/*Our first example will be a generic input validator. It asks the user
for some input, using the prompt parameter for the text of the
question. A second parameter receives a function that does the actual
work of validating the input.*/
const input = require('readline-sync');
function getValidInput(prompt, isValid) {
// Prompt the user, using the prompt string that was passed
let userInput = input.question(prompt);
// Call the boolean function isValid to check the input
while (!isValid(userInput)) {
console.log("Invalid input. Try again.");
userInput = input.question(prompt);
}
return userInput;
}
// A boolean function for validating input
let isEven = function(n) {
return Number(n) % 2 === 0;
};
console.log(getValidInput('Enter an even number:', isEven));
/*Sample Output:
Enter an even number: 3
Invalid input. Try again.
Enter an even number: 5
Invalid input. Try again.
Enter an even number: 4
4