使用JavaScript计算2个不同计划的工作小时数

时间:2016-11-10 22:21:46

标签: javascript calculator

我有一名员工需要每餐两餐,可以有不同的开始时间和不同的用餐时间

我需要得到他工作的总时间,所以让我们说一顿饭是60分钟,另一顿饭也是60分钟,总共120分钟, 但如果第二餐仍然是在第一顿饭的时间开始,则应算作一餐, 所以,如果第二顿饭开始让我们说第一餐后10分钟,那么总量应该是70分钟

var meals = [{
    "mealStartTime": 1478787000000, //9:00 AM
    "mealDuration": 60,
    "mealEndSearvingTime": 1478790600000
}, {
    "mealStartTime": 1478786400000, //9:10 AM
    "mealDuration": 60,    
    "mealEndSearvingTime": 1478790000000
}]

2 个答案:

答案 0 :(得分:2)

// It might be a good idea to use a library like BigDecimal.js
// to prevent any float point errors, or use momentjs to calculate
// the distance between to times
function msToMins(ms) {
  return ms / 1000.0 / 60.0;
}

// It's important to note that this algo assumes that:
//   * Two meals never start at the same time
//   * Meals always end after meals that started before them
function timeWorked(meals) {
  // sort by start time
  const sortedMeals = meals.sort(m => m.mealStartTime);
  
  const result = meals.reduce((prev, curr) => {
    let duration = curr.mealDuration; // extract the current meal duration

    // if the previous meal overlaps with this one
    const mealsOverlap = prev.mealEndServingTime > curr.mealStartTime;
    if (mealsOverlap) {
      // calculate the distance when the previous end and this one ends
      // the previos meal duration was fully added in the previous cycle
      duration = msToMins(curr.mealEndServingTime - prev.mealEndServingTime);
    }
    
    // return the totalDuration accumulation, with the current meal
    return Object.assign({ totalDuration: prev.totalDuration + duration }, curr);
  }, { totalDuration: 0 }); // initialize with empty object
  
  return result.totalDuration;
}

const allMeals = [
  {
    mealStartTime: 1478787000000,
    mealDuration: 60,
    mealEndServingTime: 1478790600000
  }, 
  {
    mealStartTime: 1478786400000,
    mealDuration: 60,    
    mealEndServingTime: 1478790000000
  }
];

console.log(timeWorked(allMeals));

答案 1 :(得分:2)

好吧,我的解决方案有点冗长。代码可能有点优化,但我认为方法是正确的。

我会在此处粘贴代码,您可以查看此jsfiddle以查看其是否有效。打开控制台。

所以这是代码:

Converter

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