For my homework assignment, I am developing a basic calculator application using JavaScript. My main task is to ensure that the input numbers are limited to only two and that they are valid numbers; otherwise, an error should be thrown.
Initially, concerning the addition operation exclusively, my initial code was as follows:
function add(number1, number2) {
if (arguments.length !== 2) {
throw new Error('Please provide two numbers');
}
if (!Number.isFinite(number1) || !Number.isFinite(number2)) {
throw new Error('Only numerical values are allowed');
}
return number1 + number2;
}
The code seemed functional upon testing with console.log
. However, to prevent redundancy in validations, I decided to create a separate function encapsulating these checks for reusability. Subsequently, I encountered issues with error throwing and found it perplexing.
function inputValidation(number1, number2) {
if (arguments.length !== 2) {
throw new Error('Please provide two numbers');
}
if (!Number.isFinite(number1) || !Number.isFinite(number2)) {
throw new Error('Only numerical values are allowed');
}
}
function add(number1, number2) {
inputValidation(number1, number2);
return number1 + number2;
}
While the usage of Number.isFinite
continued to operate effectively, the arguments’ length validation appeared to malfunction without clear reasoning. The test conducted produced the subsequent error message:
1) error occurs when not precisely two arguments are given
should throw Please provide two numbers:
AssertionError [ERR_ASSERTION]: Missing expected exception (Error).
I'm puzzled by this issue. Any insights would be greatly appreciated. Thank you.