Reputation: 3
I am enabled to validate a function if it is an array of two or more value
const validateZIPLength = (zip) => (
zip.length > 5 || zip.length < 5 ?
'zip code should be 5 digits': undefined
)
validateZIPLength('123')
for the above function cal, it works fine
validateZIPLength(['1234', '12345'])
it should return the zip code should be 5 and undefined but it is returning only zip code should be 5 for the 1st item in the array
Upvotes: 0
Views: 82
Reputation: 47111
Your function can only handle individual values, not arrays.
Here's how you can add support for arrays :
function validateZIPLength(zip) {
if(Array.isArray(zip)) {
for(let i = 0; i < zip.length; i++) {
zip[i] = validateZIPLength(zip[i]);
}
return zip;
} else {
return zip.length === 5 ? undefined : "zip code should be 5 digits";
}
}
console.log(validateZIPLength(['1234', '12345']));
Upvotes: 1
Reputation: 29116
validateZIPLength(['1234', '12345'])
it should return the zip code should be 5 and undefined but it is returning only zip code should be 5 for the 1st item in the array
Actually, what happens is that the function validateZIPLength
returns what you get for the entire array itself, not for the first element. When you pass in the array, it doesn't know if it got a string or an array, it simply checks the length as per zip.length > 5 || zip.length < 5
and since an array also has a length
property, the code works as you instructed it - it gets 2
because there are two elements in the array and thus returns you the string 'zip code should be 5 digits'
.
Remember, computers are stupid - they do what you tell them to, not necessarily what you want them to.
Since you have a function that takes strings and gives you results, but you want to apply it against many elements of an array, you can use .map()
which does exactly that for you. It takes a function and calls it with each member of the array. You then get a new array that contains each result.
const validateZIPLength = (zip) => (
zip.length > 5 || zip.length < 5 ?
'zip code should be 5 digits': undefined
)
const singleInvalidZIPCode = validateZIPLength('123');
const singleValidZIPCode = validateZIPLength('12345');
console.log("single invalid ZIP code:", singleInvalidZIPCode);
console.log("single valid ZIP code:", singleValidZIPCode);
const multipleZIPCodes = ['1234', '12345'].map(validateZIPLength)
console.log("multiple ZIP codes:", multipleZIPCodes);
Upvotes: 0