// 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
*/