// old:原经验,数组
// insert:新插入的时间,字符串
function newExp(old, insert) {
let oldArr = old.map(v=>v.split(' ~ '))
let insertArr = insert.split(' ~ ')
// 构造的新数组
let newArr = []
// 记录开始的时间
let start
// 是否插入结束
let finish = false // 插入结束
// 是否正在插入
let touching = false // 正在插入
for(let i=0; i<oldArr.length; i++) {
// 是否插入完成
if(finish) {
// 插入完成直接添加
newArr.push(oldArr[i])
} else {
// 正在插入(已经插入了开始)
if(touching) {
// 结束结束的位置
// 是否在中间
if(insertArr[1] < oldArr[i][1]) {
newArr.push([start, oldArr[i][1]])
finish = true
}
else if(insertArr[1]< oldArr[i+1][0]) {
// 在下一个开始前
newArr.push([start, insertArr[1]])
finish = true
}
} else {
// 开始插入
if(insertArr[0] < oldArr[i][0]) {
touching = true
start = insertArr[0]
} else if(insertArr[0] > oldArr[i][0] && insertArr[0] < oldArr[i][1]) {
touching = true
start = oldArr[i][0]
} else {
// 不满足插入条件
newArr.push(oldArr[i])
}
// 判断结束的位置
if(touching) {
// 是否在中间
if(insertArr[1] < oldArr[i][1]) {
newArr.push([start, oldArr[i][1]])
finish = true
}
else if(insertArr[1]< oldArr[i+1][0]) {
// 在下一个开始前
newArr.push([start, insertArr[1]])
finish = true
}
}
}
}
}
return newArr
}
/********* 测试 *******/
let r, n
// 测试情况一
r = [
'2015-01-01 ~ 2016-01-01',
'2017-01-01 ~ 2018-01-01'
]
n = '2015-12-01 ~ 2016-02-01'
console.log( newExp(r, n) )
console.log('==========================')
// 测试情况二
r = [
'2010-01-01 ~ 2012-01-01',
'2013-01-01 ~ 2015-01-01',
'2016-01-01 ~ 2017-01-01',
'2021-01-01 ~ 2022-10-01'
]
n = '2018-01-01 ~ 2019-01-01'
console.log( newExp(r, n) )
/*
Your previous Plain Text content is preserved below:
Given a set of non-overlapping work experiences, insert a work experience into the work experiences (merge if necessary).
You may assume that the work experiences were initially sorted according to their start times.
Example 1:
Input:
Experiences:
2015-01-01 ~ 2016-01-01
2017-01-01 ~ 2018-01-01
newExperience:
2015-12-01 ~ 2016-02-01
Output:
2015-01-01 ~ 2016-02-01
2017-01-01 ~ 2018-01-01
Example 2:
Input:
Experiences:
2010-01-01 ~ 2012-01-01
2013-01-01 ~ 2015-01-01
2016-01-01 ~ 2017-01-01
2019-01-01 ~ 2020-10-01
newExperience:
2014-01-01 ~ 2018-01-01
Output:
2010-01-01 ~ 2012-01-01
2013-01-01 ~ 2018-01-01
2019-01-01 ~ 2020-10-01
*/