我有一系列的日期范围,如下所示:
["Mon-Tue", "Mon-Wed", "Mon-Thu", "Mon-Fri", "Mon-Sat", "Mon-Sun", "Tue-Mon", "Tue-Wed", "Tue-Thu", "Tue-Fri", "Tue-Sat", "Tue-Sun", ...]
我需要创建一个大对象,该对象将这些字符串中的每个字符串映射到包含所有相关日期的数组,如下所示:

var object = {
  'Mon-Tue': ['Mon', 'Tue'],
  'Mon-Wed': ['Mon', 'Tue', 'Wed'],
}

为了提供帮助,我列出了一些可能的日子:
var days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']

无需手动完成所有操作就可以吗?

谢谢!

最佳答案

您可以使用 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; }

09-25 18:10