简体   繁体   中英

Reduce of empty array with no initial value

I'm working with fullcalendar-react and I have the following schedule, where I'm trying to get the earliest hour of the list and remove the days that are closed:

export default {
    monday: {
        startTime: '10:00',
        endTime: '23:00'
    },
    tuesday: {
        startTime: '08:00',
        endTime: '00:00'
    },
    wednesday: {
        startTime: '09:00',
        endTime: '22:00'
    },
    thursday: {
        startTime: '14:00',
        endTime: '00:00'
    },
    friday: undefined,
    saturday: {
        startTime: '13:00',
        endTime: '21:00'
    },
    sunday: undefined
}

To filter closed days and get the earliest hour, I am working around with filter and reduce, just like below:

getOpeningHour() {
    let value: any = "00:00:00";

    if (this.props.schedule) {
        const schedule = this.props.schedule; // the schedule I presented above

        if (Object.keys(schedule).length >= 1) {
            const minValue = Object.keys(schedule)
                .filter((key) => schedule[key])
                .map((key: string) => moment(schedule[key].startTime, 'HH:mm'))
                .reduce((min: moment.Moment, value: moment.Moment) => (!min || value.isBefore(min) ? value : min), moment('00:00', 'HH:mm')); 
                // Gets the earliest hour when the list is not empty, but when I give midnight as default value, it's always midnight.

            value = minValue.format('HH:mm:ss');
        }
    }
    return value;
}

When I open the calendar, I get this error:

Uncaught TypeError: Reduce of empty array with no initial value

I tried to provide , moment('00:00', 'HH:mm') as default value when the list is empty, but like this, my calendar starts always at midnight and ignores the rest, I think.

-----EDIT-----

The code is actually doing it's work and since midnight is earlier than 08:00, it will display midnight. The only thing is to display midnight only when the list is empty.

How can I fix this issue when I am working with moment() hours? Thank you!

Try moment('24:00', 'HH:mm') :

const hourTemplate = 'HH:mm';

const getEarliersHour = schedule =>
  Object.values(schedule)
    .filter(value => value)                  // no undefined
    .map(time => moment(time.startTime, hourTemplate))
    .reduce(
      (min, curr) => (curr.isBefore(min) ? curr : min),
      moment('24:00', hourTemplate)         // latest moment
    )
    .format(hourTemplate);

getEarliersHour(schedule);                  // 08:00
getEarliersHour({});                        // 00:00

Demo:

编辑cold-sunset-oc7fy

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM