JS求助,计算2个时间段之间的重复和空隙值,并合并

现在有这么个需求,暂且只有2个时间段需要处理(设置时间价格)。
假若已经存在时间段 2017-02-03 至 2017-02-12 (暂且成为时间段A),有下面情况:
1.这时候新增时间段 2017-02-10 至 2017-02-20(暂且成为时间段B) 。这时候2个时间段之间是存在重叠部分,我想将重叠部分提取出来,用后期新增价格覆盖之前已存在的,并将时间段B和成为时间段A合并起来。

2.新增的时间段为 2017-02-15 至 2017-02-20(暂且成为时间段C) 这时候和已经存在的最后2017-02-12之间是存在间隙值,我这时候也需要将这间隙值拿出来设置特殊的价格,最后合并时间段A、间隙时间段、时间段C。

求个思路,谢谢。

阅读 5.2k
3 个回答

我猜你的意思是合并时间段,添加价格断点?


我的思路是就是重新整理时间段,再做价格处理

let costA = ['2017-08-01','2017-08-05'];
let costB = ['2017-08-03','2017-08-12'];
let costC = ['2017-08-08','2017-08-12'];
function concat(cost1, cost2){
  let temp = [...cost1,...cost2];
  temp.sort((a,b) => a > b);
  let newMidStart = temp.findIndex(d => d == cost2[0]);
  let newCost1 = temp.splice(0, newMidStart);
  let newCost2 = temp;
  let newCost3;
  if (newCost1.length < newCost2.length){
    newCost1 = [newCost1[0], newCost2[0]];
    newCost2 = [newCost2[0], newCost2[2]];
  } else if (newCost1.length == newCost2.length && newCost1[1] != newCost2[0]){
    newCost3 = [newCost1[1], newCost2[0]];
  }
  console.log(newCost1, newCost2, newCost3);
}
concat(costA, costB);
concat(costA, costC);
var testAB = [{
    startTime: "2017-02-03",
    endTime: "2017-02-12",
    price: 680,
},{
    startTime: "2017-02-10",
    endTime: "2017-02-20",
    price: 780,
}];
var testAC = [{
    startTime: "2017-02-03",
    endTime: "2017-02-12",
    price: 680,
},{
    startTime: "2017-02-15",
    endTime: "2017-02-20",
    price: 980,
}];

function test (list) {
    let specailPrice = "1100";
    let newArray = [];
    if (list.length && list.length === 0) {
        return false;
    }
    let length = list.length;
    for (let i = 1; i < length; i++) {
        let start = new Date(list[i].startTime).getTime();
        let lastEnd = new Date(list[i-1].endTime).getTime();
        if (start > lastEnd) { //有缝隙
            newArray.push({
                startTime: list[i-1].startTime,
                endTime: list[i-1].endTime,
                price: list[i-1].price,
            });
            newArray.push({
                startTime: list[i-1].endTime,
                endTime: list[i].startTime,
                price: specailPrice,
            });
        } else { //无缝隙 或者重叠
            newArray.push({
                startTime: list[i-1].startTime,
                endTime: list[i].startTime,
                price: list[i-1].price,
            })
        }
    }
    newArray.push(list[length-1])
    console.log(newArray);
}

test(testAB);
test(testAC);

大概我猜测你是这个意思

首先判断两个时间段是否有重合:

if(startTimeA < endTimeB || startTimeB < endTimeA)

有重合就算费用

//开始时间
Date startTime = Math.min(startTimeA, startTimeB);
Date midTime = Math.max(startTimeA, startTimeB);
Date endTime = Math.max(endTimeA, endTimeB);

int totalCost = unitCost1 * (midTime - startTime) + unitCost2 * (endTime - midTime);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题