Вы можете взять Map
для получения дней с индексом и повторять, пока не получите все дни.
var days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
daysMap = new Map(days.map((d, i) => [d, i])),
data = ["Mon-Tue", "Mon-Wed", "Mon-Thu", "Mon-Fri", "Mon-Sat", "Mon-Sun", "Tue-Mon", "Tue-Wed", "Tue-Thu", "Tue-Fri", "Tue-Sat", "Tue-Sun"],
result = Object.assign({}, ...data.map(d => {
var [start, end] = d.split('-'),
temp = [],
s = daysMap.get(start),
e = daysMap.get(end);
while (s !== e) {
temp.push(days[s]);
s++;
s %= days.length
}
temp.push(days[s]);
return { [d]: temp };
}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Если хотите, вы можете взять Generator
на требуемые дни.
function* getDays(from, to) {
var days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
i = days.indexOf(from);
while (days[i % days.length] !== to) yield days[i++ % days.length];
yield days[i % days.length];
}
var data = ["Fri-Tue", "Mon-Tue", "Mon-Wed", "Mon-Thu", "Mon-Fri", "Mon-Sat", "Mon-Sun", "Tue-Mon", "Tue-Wed", "Tue-Thu", "Tue-Fri", "Tue-Sat", "Tue-Sun"],
result = Object.assign({}, ...data.map(d => ({ [d]: [...getDays(...d.split('-'))] })));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Другой подход с использованием объекта завтрашнего дня, который дает день завтрашнего дня.
function* getDays(from, to) {
var tomorrow = { Sun: 'Mon', Mon: 'Tue', Tue: 'Wed', Wed: 'Thu', Thu: 'Fri', Fri: 'Sat', Sat: 'Sun' };
yield from;
while (from !== to) yield from = tomorrow[from];
}
var data = ["Fri-Tue", "Mon-Tue", "Mon-Wed", "Mon-Thu", "Mon-Fri", "Mon-Sat", "Mon-Sun", "Tue-Mon", "Tue-Wed", "Tue-Thu", "Tue-Fri", "Tue-Sat", "Tue-Sun"],
result = Object.assign({}, ...data.map(d => ({ [d]: [...getDays(...d.split('-'))] })));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }