我想制作班次解析器助手,它是生成工作班次的时间,下面是班次规则 let shift_rule = [ { shift: '07-12', start: 7, finish: 12 }, { shift: '12-17', start: 12, finish: 17 }, { shift: '17-22', start: 17, finish: 22 }, ];如果时移是timeStart = 7,timeFinish = 17预期输出:[ { shift: '07-12', start: 7, finish: 12 }, { shift: '12-17' start: 12, finish: 17 },]我已经尝试用这段代码解决shift_rule .map((time) => ((timeFinish > time.start)) && time) .filter(item => typeof item !== 'boolean');但是当 filter 是time.start = 17,时timeFinish = 22,它显示:[ { shift: '07-12', start: 7, finish: 12 }, { shift: '12-17', start: 12, finish: 17 }, { shift: '17-22', start: 17, finish: 22 }, ]希望可以用ES6 Functional解决
1 回答
慕容708150
TA贡献1831条经验 获得超4个赞
您可以通过检查每个范围的开始是否在另一个范围的结束之前来检查重叠的时间范围(例如,参见这个问题)。您可以在过滤器中实现该代码,然后使用 map 仅返回班次名称:
let shift_rule = [
{ shift: '07-12', start: 7, finish: 12 },
{ shift: '12-17', start: 12, finish: 17 },
{ shift: '17-22', start: 17, finish: 22 }
];
const filter_shifts = (rules, timeStart, timeFinish) =>
rules.filter(s => s.start < timeFinish && s.finish > timeStart).map(s => s.shift);
console.log(filter_shifts(shift_rule, 7, 17));
console.log(filter_shifts(shift_rule, 17, 22));
添加回答
举报
0/150
提交
取消