简体   繁体   English

使用reduce将一系列日期映射到时隙

[英]mapping a range of dates to time slots with reduce

I have a class TimeSlotEntity and I have a range object with dates, that's, roughly speaking, is like this:我有一个 class TimeSlotEntity并且我有一个带有日期的 object 范围,大致来说是这样的:

const slotRange = ['15:00', '15:30', '16:00', '16:30', '17:00', '17:30', '18:00'];

In code it looks like this:在代码中它看起来像这样:

const range = moments.range(startEventTime, endEventTime).by('minutes', { step: 30 });

The TimeSlotEntity class has date setters: setDateFrom(val: Moment) , setDateTo(val: Moment) ; TimeSlotEntity class 有日期设置器: setDateFrom(val: Moment) , setDateTo(val: Moment) ;

I would like to map the range to the corresponding TimeSlotEntity s so that the first slot would be from 15:00 to 15:30, the second one from 15:30 to 16:00, the third one from 16:00 to 16:30 etc.我想将 map 的范围设置为相应的TimeSlotEntity ,以便第一个时段从 15:00 到 15:30,第二个从 15:30 到 16:00,第三个从 16:00 到 16: 30等

How to do this with the javascript reduce function?如何使用 javascript 减少 function?

I know you asked specifically to use reduce , but I'd still just go with good old for loops.我知道你特别要求使用reduce ,但我仍然只是 go 和旧for循环。

const rangesArray = Array.from(ranges);

const timeSlotEntities = [];
for (let i = 0; i < rangesArray.length - 1; i++) {
  const timeSlotEntity = new TimeSlotEntity();

  timeSlotEntity.setDateFrom(rangesArray[i]);
  timeSlotEntity.setDateTo(rangesArray[i + 1]);

  timeSlotEntities.push(timeSlotEntity);
}

It would only work if the ranges array contains at least two elements.仅当ranges数组包含至少两个元素时才有效。

If TimeSlotEntity can have an undefined end date, then you can modify the loop condition to i < ranges.length and that would work with ranges with only one element.如果TimeSlotEntity可以有一个undefined的结束日期,那么您可以将循环条件修改为i < ranges.length并且这将适用于只有一个元素的ranges

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM