#简介
需求需要前端验证a,b,c,d四段时间,要求自由选择时间,且全天的时间都被选择到并且没有重叠,即以下的格式
jsconst periods = { time1: ["00:00-12:00", "18:00-23:00"], time2: ["12:00-18:00"], time3: ["23:00-24:00"], time4: [], };
#代码
- 把小时:分钟转为分钟数,然后从小到大排序
- 开始分钟为0,结束分钟为24*60
- 遍历排序后的分钟数,获取start minute和end minute
- 如果上一段的end比下一段的start大,则说明有重叠,返回false
- 校验都通过,证明全天都被选择,返回true
jsconst usePeriodValidate = (periods) => { /** * @description: 时间格式化函数 * @param {*} periodStr */ const parsePeriods = (periodStr) => { return periodStr.split(" ").map((period) => { const [start, end] = period.split("-").map((t) => { const [h, m] = t.split(":").map(Number); return h * 60 + m; }); return { start, end }; }); }; const allPeriods = []; /** * @description: 遍历所有时间段并添加到数组中去 */ Object.values(periods).forEach((periodArr) => { if (periodArr.length) { periodArr.forEach((periodStr) => { allPeriods.push(...parsePeriods(periodStr)); }); } }); // 排序 allPeriods.sort((a, b) => a.start - b.start); let isCovered = true; // 全天覆盖 let firstStart = allPeriods[0].start; // 起始时间 let lastEnd = 0; // 收尾时间 if (firstStart !== 0) { console.error("时间段未覆盖24小时"); isCovered = false; } /** * @description: 如果下一段时间段start比上一段end小,即重叠 */ for (const { start, end } of allPeriods) { if (start < lastEnd) { console.error("时间段重叠"); isCovered = false; break; } lastEnd = end; } /** * @description: 如果不是以00:00-24:00结束,则校验失败 */ if (lastEnd !== 24 * 60) { console.error("时间段未覆盖24小时"); isCovered = false; } if (isCovered) { console.log("时间段校验通过"); } else { console.log("时间段校验失败"); } }; const periods = { time1: ["00:00-12:00", "18:00-23:00"], time2: ["12:00-18:00"], time3: ["23:00-24:00"], time4: [], }; usePeriodValidate(periods);