calculator - Calculate hours worked from 2 different schedules with JavaScript -


i have employee needs serve 2 meals each meal can have different start time , different meal duration

i need total time worked, let's 1 meal 60 minutes , meal 60 minutes total 120 minutes, if second meal started still in time of first meal should counted one, if second meal started let's 10 minutes after first meal total should 70 min

 var meals = [{     "mealstarttime": 1478787000000, //9:00     "mealduration": 60,     "mealendsearvingtime": 1478790600000 }, {     "mealstarttime": 1478786400000, //9:10     "mealduration": 60,         "mealendsearvingtime": 1478790000000 }] 

well, solution bit lengthy. code bit optimized think approach right.

i'll paste code here , can check out jsfiddle see work. open console though.

so here's code:

function gettotalworkhours(meals){     var punches = [], startcount = 0, endcount = 0, accountablepunchpairs = [], hoursworked = 0;    //// populate array of punches ///   meals.foreach(function(meal) {     punches.push({         type:'start',       timestamp: meal.mealstarttime,        inenglishplease: new date(meal.mealstarttime).tolocalestring()     });     punches.push({         type: 'end',       timestamp: meal.mealendservingtime,        inenglishplease: new date(meal.mealendservingtime).tolocalestring()     });     });    /// sort punches time ///   punches.sort(function(a, b){     return a.timestamp - b.timestamp;     });     /// filter out accountable punches.   /// save punches array of start/end pairs.   /// accountable punches did not occur   /// while employee busy other meals   punches.foreach(function(punch){     if(punch.type === 'start'){         if(++startcount - endcount === 1) accountablepunchpairs.push([punch]);     }     if(punch.type === 'end'){         if(++endcount === startcount) {         accountablepunchpairs[accountablepunchpairs.length-1][1] = punch;       }     }   });    /// calculating total hours based   /// on accountable punch pairs   accountablepunchpairs.foreach(function(punchpair){     hoursworked += (punchpair[1].timestamp - punchpair[0].timestamp) / 3600000;   });    return hoursworked; } 

https://jsfiddle.net/friedman5764/4nyv5um0/


Comments

Popular posts from this blog

sql server - Cannot query correctly (MSSQL - PHP - JSON) -

php - trouble displaying mysqli database results in correct order -

C++ Linked List -