Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a string based off of an objects key value pairs

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.

like image 208
peters313 Avatar asked Dec 15 '25 18:12

peters313


1 Answers

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(', ');
}
like image 192
Darren Avatar answered Dec 17 '25 10:12

Darren



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!