Imagine a scenario where there is a selection of days available to the user (they can choose multiple).
The list includes Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, and Saturday, each with an associated number from 0 to 6. For instance, Sunday corresponds to 0 and Saturday to 6:
vm.weekDays = [
{name: 'Sunday', number: 0},
{name: 'Monday', number: 1},
{name: 'Tuesday', number: 2},
{name: 'Wednesday', number: 3},
{name: 'Thursday', number: 4},
{name: 'Friday', number: 5},
{name: 'Saturday', number: 6},
]
If the user selects Sunday, Monday, and Tuesday, the output should be "Sunday - Tuesday". However, if they select Sunday, Monday, Tuesday, and Thursday, it should display as "Sunday - Tuesday, Thursday". Finally, choosing Sunday, Tuesday, and Thursday should show exactly those selected days.
To store these selections and display them accordingly, I am saving the strings in an array. Here is what I have implemented so far:
function test() {
vm.display = [];
var sortedWeekdays = _.sortBy(vm.sWeekDays, 'number');
var start = 0;
var end = 0;
if(sortedWeekdays.length > 1){
for(var i=0; i <= sortedWeekdays.length-2; i++){
if(sortedWeekdays[i].number + 1 != sortedWeekdays[i+1].number) {
start = i + 1;
end = i;
vm.display.push(sortedWeekdays[i].name);
}
end = i + 1;
}
vm.display.push(sortedWeekdays[start].name + " - " + sortedWeekdays[end].name);
} else {
vm.display.push(sortedWeekdays[0].name);
}
}
Currently, the function successfully displays consecutive days, but selecting Sunday through Tuesday and Thursday does not yield the desired outcome.
If you have any suggestions or solutions, your assistance would be highly appreciated.