时间段的非交集时间段如何算?

现在我有一些时间比如

上午08:30-11:30,下午12:30-17:30,晚上18:30-21:00 是我的排班时间,然后

09:30-12:00
08:30-10:00
13:00-15:00
19:00-20:00

这些时间是别人替我的班的时间,是不定数量的,现在需要算出我的班次生效时间,就是从我的排班时间里把别人替班的时间减掉,上面给的例子得到我的生效时间为:

下午12:30-13:00   15:00-17:30 晚上18:30-19:00 20:00-21:00

本来我的思路是:

先取所有的替班时间得并集,然后再用排班时间分成特定部分,
然后每个部分和排班部分一个一个做差集,最后得到生效时间

但是写起代码发现难度有点大,一直没有写出来,也找过一些库,比如moment-range ,这些库,有提供多个时间段之间取交集,差集,和并集的API,但是这些API和实际的需求还有很多的出入,不能直接用,求大神指点,有没其他思路或者有没有代码的指点。

阅读 1.8k
2 个回答

把时间转换为字符串,然后比较大小就简单了

// 初始时间段
let myTimes = ["08:30-11:30","12:30-17:30","18:30-21:00"];
let otherTimes = ["09:30-12:00","08:30-10:00","13:00-15:00","19:00-20:00"];

// 转换一下,变二维数组
myTimes = myTimes.map(time => time.replace(/:/g, '').split('-'));
otherTimes = otherTimes.map(time => time.replace(/:/g, '').split('-'));

otherTimes.forEach(([otherStart, otherEnd]) => {
  for (let i = 0; i < myTimes.length; i ++) {
    const [myStart, myEnd] = myTimes[i]
    if (otherStart > myStart && otherEnd < myEnd) {
      myTimes[i][0] = otherEnd;
      myTimes.splice(i, 0, [myStart, otherStart]);
      i++;
    } else if (otherEnd < myEnd && otherEnd > myStart) {
      myTimes[i][0] = otherEnd
    } else if (otherStart > myStart && otherStart < myEnd) {
      myTimes[i][1] = otherStart
    } else if (otherStart <= myStart && otherEnd >= myEnd) {
      myTimes.splice(i, 1);
      i--;
    }
  }
});
console.log(myTimes)
const arranged = ["08:30-11:30", "12:30-17:30", "18:30-21:00"];
const rids = ["09:30-12:00", "08:30-10:00", "13:00-15:00", "19:00-20:00"];

const r = rids.map(s => s.split("-"))
    .reduce((result, range) => {
        return result.flatMap(segment => {
            if (segment[1] <= range[0] || segment[0] >= range[1]) {
                return [segment];
            }
            return [
                [segment[0], range[0]],
                [range[1], segment[1]]
            ].filter(([a, b]) => a < b);
        });
    }, arranged.map(s => s.split("-")));

console.log(r);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题