'Find consecutive login timings from javascript array list

I have an array of objects in javascript where I have employees login timings. I want to find if an employee has worked more then 5 hours consecutively then he/she will get a break. Otherwise if an employee worked more than 5 hours, but not consecutively, then they do not get a break.

Here is the code - it currently is just checking the number of hours an employee has worked, but it is not checking for consecutive hours.

checkBreakTimings() {

    let breakTimes = "";
    

    const timings = [
        {
       timeIn: '11:00',
       timeOut: '12:00',        
        },
        {
       timeIn: '12:00',
       timeOut: '13:00',        
        },
        {
       timeIn: '14:00',
       timeOut: '16:00',        
        },
        {
       timeIn: '16:00',
       timeOut: '18:00',        
        }
    ];

   let h = 0;
   
      timings.forEach(e => {
        const ms = moment(e.timeOut, "HH:mm").diff(moment(e.timeIn, "HH:mm"));
        h = h + = Number(moment.duration(ms).asHours());
      });
  
      if(h > 5 )
      {
        breakTimes = "Yes";
      }
    }
    
    return breakTimes;
  }

As you can see from the above timings that an employee worked 8 hours out for which 6 hours are consecutive from 14:00 to 18:00 here break will be applied, but the above 2 timings are not consecutively more than 5 hours.

My problem is - is there any way to find out the number of consecutive hours from an array using JavaScript or in moment.js



Solution 1:[1]

Here is a function that could do the trick

function isAllowedBrake(times) {
  let isAllowed = false
  let consecutive = 0;
  let lastVal

  times.forEach((e) => {
    if (lastVal && moment(lastVal, "HH:mm").isBefore(moment(e.timeIn, "HH:mm"))) {
      consecutive = 0
    }
    const ms = moment(e.timeOut, "HH:mm").diff(moment(e.timeIn, "HH:mm"));
    let duration = Number(moment.duration(ms).asHours())
    consecutive += duration
    lastVal = e.timeOut
  })

  if (consecutive > 5) {
    isAllowed = true;
  }

  return isAllowed;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rosmak