I’m new to JavaScript and I’m having trouble doing this question and I was wondering if this can work. This is the task.
Write a function
toIPv4
, which allows the caller to pass 4 String
values and returns a valid IP Address as a String. In your solution,
you must do the following:
- Use either arguments or a Rest Parameter to accept multiple values to your function
- Make sure the caller passes exactly 4 parameters, error if not
- Make sure all 4 values are Strings, error if not
- Convert each string value to a number (Integer) and make sure it is in the range 0-255, error if not
- If all of the above checks pass, use a Template Literal to return the IP Address as a String
- Use the functions from questions 1 and 2 to help you solve 1-5 above For example, toIPv4(“192”, “127”, “50”, “1”) should return
“192.127.50.1”
function toIPv4(...args) {
// Check if exactly 4 arguments are passed
if (args.length !== 4) {
throw new Error('You must pass exactly 4 parameters.');
}
// Check if all arguments are strings and are valid numbers in the range 0-255
const numbers = args.map(arg => {
if (typeof arg !== 'string') {
throw new Error('All arguments must be strings.');
}
const num = parseInt(arg, 10); // Convert the string to a number (integer)
if (isNaN(num) || num < 0 || num > 255) {
throw new Error('Each string must represent a valid number between 0 and 255.');
}
return num;
});
// Use Template Literal to return the IP Address as a String
return `${numbers[0]}.${numbers[1]}.${numbers[2]}.${numbers[3]}`;
}
I’m trying to put the example as the input and it doesn’t work