JSFiddle - React, Tailwind, and code Playground

by friedman5764

JavaScript

var meals = [
	{
    "mealStartTime": 1478787000000, //9:00 AM
    "mealDuration": 60,
    "mealEndServingTime": 1478790000000 //10:10 AM
	}, 
  {
    "mealStartTime": 1478786400000, //9:10 AM
    "mealDuration": 60,    
    "mealEndServingTime": 1478790600000 //10:10 AM
	},
  {
    "mealStartTime": 1478793600000, //11:10 AM
    "mealDuration": 45,    
    "mealEndServingTime": 1478796300000 //11:45 AM
	}
];

getTotalWorkHours(meals);

function getTotalWorkHours(meals){
	var punches = [], startCount = 0, endCount = 0, accountablePunchPairs = [], hoursWorked = 0;
  
  //// Populate an array of all 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 the punches by time ///
  punches.sort(function(a, b){
    return a.timestamp - b.timestamp;
	});
  
  console.log('Now we have an array of all punches sorted by time:');
  console.log(punches);
  
  /// Filter out only the accountable punches.
  /// We will save the punches as an array of start/end pairs.
	/// Accountable punches are those that did not occur
  /// while the employee was busy with 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;
      }
    }
  });
  
  console.log('Accountable Punch Pairs:');
  console.log(accountablePunchPairs);
  
  /// Now just calculating the total hours based
  /// on the accountable punch pairs
	accountablePunchPairs.forEach(function(punchPair){
  	hoursWorked += (punchPair[1].timestamp - punchPair[0].timestamp)...