I have array of objects in javascript where i have employees login timings.I want to find if employee worked more then 5 hours consecutively then he/she will get break. otherwise if employee worked more then 5 hours but not worked consecutively then no break.
here is the code it just checking the no of hours employee worked but not checking consecutively 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;
}
if you can see the above timings employee worked 8 hours out for which 6 hours are consecutive form 14:00 to 18:00 here break will be apply but the above 2 timings are not consecutively more then 5 hours.
My problem is there any way to find out the number of consecutive hours from array using JavaScript or in moment.js
CodePudding user response:
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;
}
CodePudding user response:
Try like following snippet:
const checkBreakTimings = () => {
let breakTimes = "";
const timings = [
{timeIn: '11:15', timeOut: '12:00', },
{timeIn: '12:00', timeOut: '13:00', },
{timeIn: '13:00', timeOut: '15:46', },
{timeIn: '16:00', timeOut: '18:00', }
];
let h = 0;
let consecutive = 0
let lastOut = null
timings.forEach(e => {
const ms = moment(e.timeOut, "HH:mm").diff(moment(e.timeIn, "HH:mm"));
let worked = Number(moment.duration(ms).asHours())
consecutive = worked
if (lastOut === e.timeIn) { // 