I’m working on a React project where I need to map numeric day values (e.g., 0 for Sunday, 1 for Monday, etc.) to their corresponding day names (in both English and French) based on the user’s locale. I’m using intl.formatMessage
for localization and have a helper function to get the translated day names.
Here’s my retrieveWeekDays
function:
export const retrieveWeekDays = intl => {
return [
{ key: 'selectAll', label: intl.formatMessage({ ...translations.days.allDays }), value: 'All' },
{ key: 0, label: intl.formatMessage({ ...translations.days.sunday }), value: 'Sunday' },
{ key: 1, label: intl.formatMessage({ ...translations.days.monday }), value: 'Monday' },
{ key: 2, label: intl.formatMessage({ ...translations.days.tuesday }), value: 'Tuesday' },
{ key: 3, label: intl.formatMessage({ ...translations.days.wednesday }), value: 'Wednesday' },
{ key: 4, label: intl.formatMessage({ ...translations.days.thursday }), value: 'Thursday' },
{ key: 5, label: intl.formatMessage({ ...translations.days.friday }), value: 'Friday' },
{ key: 6, label: intl.formatMessage({ ...translations.days.saturday }), value: 'Saturday' },
];
};
Here’s my current working code for mapping the days:
case 5:
const mappedDayNames = parsedData.permittedDays
.map(day => {
const matchingDay = weekDaysArray.find(dayObj => dayObj.key === day);
return matchingDay ? matchingDay.label : ''; // Safely access `label`
})
.filter(Boolean); // Remove any empty strings in case a day was not found
// Join the day names with a comma separator
const formattedDayList = mappedDayNames.join(', ');
resultMessage = intl.formatMessage(
{ ...translations.rules.applicableOnSpecificDays },
{ permittedDays: formattedDayList }
);
break;
In this case, weekDaysArray
is fetched using the retrieveWeekDays(intl)
function, which returns an array of objects containing the key (numeric day) and label (translated day name) for the respective locale.
Problem Statement:
This code works fine, but I’m wondering if there’s a more efficient or better way to handle this scenario. Is there any way to improve performance or simplify this process further?