I have a function which from an array of days return the array of days with it's date like from array of
['Sun', 'Mon', 'Tue', 'Wed' ] my function returns the days from today if there are some past days i switch the date to next week so the array will become ['Wed 23', 'Sun 27', 'Mon 28', 'Tue 29' ]
And here is how my function looks like (i've added all comments that specify what i'm doing on each step:
moment.locale('it'); // setting locale to italian as API response returns it formatted days
const days = ['lun', 'mar', 'mer', 'gio', 'ven', 'sab', 'dom']; // mapping weekdays which will be used to get index of the day to use in isoWeekday
const momentToday = moment().isoWeekday(); // setting today date
const arrayGiorni = giorni.map((g) => {
const dayIndex = days.indexOf(g.giorno.toLowerCase()); // getting index of day from the object array es if g.giorno is 'mar' index will be 2
if (momentToday <= dayIndex) { // checking if today is <= to mapping object then adding it to array
return {
id: g.id,
giorno: moment().isoWeekday(dayIndex),
};
} else { // else skipping to next week and adding the object to array
return {
id: g.id,
giorno: moment()
.add(1, 'weeks')
.isoWeekday(dayIndex),
};
}
});
// sorting the array to get an ordered array of dates
arrayGiorni.sort((a, b) => moment(a.giorno).valueOf() - moment(b.giorno).valueOf());
// formatting the moment object to get string formatted date
this.giorni = arrayGiorni.map(g => g.giorno.format('ddd DD MMM'));
console.log(this.giorni);
As asked in comments here is the model of giorni:
export class NegozioGiorni {
constructor(
public id: number,
public giorno: string,
public orari: string[] = []
) {}
}
That in array of objects will be [ { id: 1, giorno: 'lun', orari: ['12:00', '13:00'] }, { id: 2, giorno: 'mer', orari: ['12:00', '13:00'] }, { id: 2, giorno: 'ven', orari: ['15:00', '17:00'] } ]
I was wondering if there is something that i can reduce in this come and if there is a way to make it more performable.