I am using the map function with an if statement that doesn’t end in else. I have to be strict that only the defined recourseTypes are shown.
in eslint I get an error on my => as it doesn’t end in an else
Array.prototype.map() expects a value to be returned at the end of arrow function.
Is there a correct way to write this?
Code:
routes: async () => { const apiURL = process.env.BASE_URL const response = await axios.get(`${apiURL}/urls`) const { data: resources } = response.data const urlModule = resources.map((resource) => { const { resourceType } = resource if (resourceType === 'brand') { return { url: `/${resource.url}`, changefreq: 'weekly', priority: 0.9, } } else if (resourceType === 'product') { return { url: `/${resource.url}`, changefreq: 'monthly', priority: 0.8, } } else if (resourceType === 'category') { return { url: `/${resource.url}`, changefreq: 'weekly', priority: 0.7, } } else if (resourceType === 'document') { return { url: `/${resource.url}`, changefreq: 'weekly', priority: 0.6, } } }) return [ { url: '/', changefreq: 'daily', priority: 1, }, { url: '/account', changefreq: 'daily', priority: 1, }, { url: '/account/order-history', changefreq: 'daily', priority: 1, }, ...urlModule, ] },
Advertisement
Answer
Clarification : resources
array contains all the resourceType that we are comparing using if/else
clause ? As Array.map()
will return the same number of elements as input array contains otherwise it will return with undefined.
Suggestion : Instead of multiple if/else-if
clause, we can use multiple if
statements for a better performance.
Demo :
// Response coming from API. const resources = [{ resourceType: 'brand', url: 'brandUrl' }, { resourceType: 'product', url: 'productUrl' }, { resourceType: 'category', url: 'categoryUrl' }, { resourceType: 'document', url: 'documentUrl' }]; // Array of required ResourceTypes. const requiredResourceTypes = ['brand', 'product', 'document']; // Logic to filter and get the URL's object of the required resourceTypes. const urlModule = resources.filter(({resourceType}) => requiredResourceTypes.includes(resourceType)).map((resource) => { const { resourceType } = resource if (resourceType === 'brand') { return { url: `/${resource.url}`, changefreq: 'weekly', priority: 0.9, } } if (resourceType === 'product') { return { url: `/${resource.url}`, changefreq: 'monthly', priority: 0.8, } } if (resourceType === 'category') { return { url: `/${resource.url}`, changefreq: 'weekly', priority: 0.7, } } if (resourceType === 'document') { return { url: `/${resource.url}`, changefreq: 'weekly', priority: 0.6, } } }); console.log(urlModule);
Performance test result screenshot :