I am writing a JavaScript application and would like to validate function arguments in many places. Most of these checks will be for correct argument types, or numeric values within specific ranges.
Here is a simple function I came up with to check any number of preconditions:
function requires(conditions)
{
for (var cond in arguments)
{
if (typeof cond !== "boolean") throw "Preconditions must be boolean expressions {" + cond + "}";
if (cond !== true) throw "Precondition failed {" + cond + "}";
}
}
It would be used like this:
function alertChar(message, index)
{
requires(
typeof message === "string",
typeof index === "number",
index >= 0,
index < message.length);
alert(message.charAt(index));
}
Is there anything conceptually wrong with this simple implementation? Is there a way I can make it lazily evaluate each precondition expression? Is accessing the arguments
array inefficient?