需要合并连续的数字
- 如:[1, 6, 7, 9, 13, 14, 15, 17, 18, 20] //需要转换成[‘1’, ‘6->7’, ‘9’, ‘13->15’, ‘17->18’, ‘20’]
//实现以下转换,合并连续的数字
const list: number[] = [1, 6, 7, 9, 13, 14, 15, 17, 18, 20] //需要转换成['1', '6->7', '9', '13->15', '17->18', '20']
let start: number = list[0] //记录连续数字的开始位置
const resultList: string[] = [] //输出的结果
const continuity = (index: number): string[] => {
if (index >= list.length) {
return []
}
if (list[index + 1] - list[index] === 1) {
continuity(index + 1) //为连续数字,继续执行此方法
} else {
if (start !== list[index]) {
resultList.push(`${start}->${list[index]}`)
} else {
resultList.push(`${start}`)
}
start = list[index + 1]
continuity(index + 1)
}
return resultList
}
console.log(continuity(0)) // ['1', '6->7', '9', '13->15', '17->18', '20']