I currently receive an object from a payload that I'm looking to format essentially into a string based off the values inside that object. I have a solution but I'm not really a big fan of it and know there is likely a more practical way of solving this.
the object that comes back in the payload looks like this
{
sundayUsage: false,
mondayUsage: true,
tuesdayUsage: false,
wednesdayUsage: true,
thursdayUsage: true,
fridayUsage: true,
saturdayUsage: false
}
Based off of these values I want to be able to display a different string.
Here is my current solution
function formatSchedule(schedule) {
let days = []
let convertedSchedule = Object.keys(schedule).map(x => ({
available: schedule[x],
label: x.slice(0, 3).replace(/^[^ ]/g, match => match.toUpperCase())
}))
convertedSchedule.map(x => {
if (x.available) {
days.push(x.label)
}
return days
})
if (
days.includes('Mon' && 'Tue' && 'Wed' && 'Thu' && 'Fri' && 'Sat' && 'Sun')
) {
return 'Everyday'
} else if (
days.includes('Mon' && 'Tue' && 'Wed' && 'Thu' && 'Fri') &&
!days.includes('Sat' && 'Sun')
) {
return 'Weekdays (Mon-Fri)'
} else if (
days.includes('Sat' && 'Sun') &&
!days.includes('Mon' && 'Tue' && 'Wed' && 'Thu' && 'Fri')
) {
return 'Weekends (Sat-Sun)'
} else return days.join(', ')
}
I don't feel like bringing in an external library is the necessary, but I am open to looking into suggestions if it ends up being the right tool for the job.
Slightly different approach, using Boolean as the function passed to some/every:
function formatSchedule(schedule) {
const days = Object.values(schedule);
const weekdays = days.slice(0, 5);
const weekend = days.slice(-2);
if (days.every(Boolean)) return 'Everyday';
else if (weekdays.every(Boolean) && !weekend.some(Boolean)) return 'Weekdays (Mon-Fri)'
else if (weekend.every(Boolean) && !weekdays.some(Boolean)) return 'Weekends (Sat-Sun)'
else return Object.entries(schedule)
.filter(v => v[1])
.map(v => v[0][0].toUpperCase() + v[0].slice(1, 3))
.join(', ');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With