猛跑小豬
2023-03-24 16:37:29
我想制作班次解析器助手,它是生成工作班次的時間,下面是班次規(guī)則 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 },]我已經(jīng)嘗試用這段代碼解決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條經(jīng)驗 獲得超4個贊
您可以通過檢查每個范圍的開始是否在另一個范圍的結(jié)束之前來檢查重疊的時間范圍(例如,參見這個問題)。您可以在過濾器中實現(xiàn)該代碼,然后使用 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
提交
取消