I do a lot of programming in my class. It's just my first semester, and most of my stuff is review. I've taken to using a verifyInput function to ensure that user inputs match certain criteria. Since I end up using verifyInput so much, I keep coming up with more ways to enhance and expand it. At the moment, my code looks something like this:
function verifyInput(foo, match, response = ": is not a valid input.") {
const input = foo()
if (!isNaN(input) && !input || input === null || input === undefined) {
if (input === null) {
return null;
}
else {
alert("Not valid.");
}
return verifyInput(foo, match, response);
}
else {
if (match && !match(input)) {
alert("(" + input + ")" + response);
return verifyInput(foo, match, response);
}
else {
return input;
}
}
}
userInput = verifyInput(() => prompt("Input?"), (x) => x > 10 ? true : false)
Works like a charm. Frequently I think up new things to add to it. Recently I was considering adding an additional parameter to modify the output string. Maybe I want the user to be able to input numbers as spelt strings instead of regular values. A user could input "seven"
and it would validate and return 7.
After some thought I realized that I could use my match function as both a validator and an output modifier. However I do this sort of thing a lot when working on old and new functions. I was curious what sort of guidelines and techniques others use to manage their functions and parameters. Also, how do you organize them?