如何在推入 javascript 数组之前跟踪连续范围并验证新范围?

how to keep track of continuous ranges and validate new ones before pushing in javascript array?

我们在二维数组中有一些频率范围。内部数组保持频率上限和下限,外部数组是排序范围的列表:

/*
[
[L0,U0],
[L1,U1],
[L2,U2]
]
*/

let freqList = [
[272.50,275.86],
[279.18,283.34],
[288.78,293.12]
]

新范围不应与保存的范围重叠,我如何验证新范围并将它们推送到确切的数组索引?

我认为您只需要找到第一个索引,使其较低的数字大于您的较低数字。确保您的较大数字也低于较小的数字。确保前面的元素更大的数字小于你的小数字。然后将其切成该索引:

let freqList = [
    [272.50,275.86],
    [279.18,283.34],
    [288.78,293.12]
]

const addRange = (min, max) => {
    if (min > max) {
    throw new Error('invalid')
    }
    // find the first element where the min element is greater than the current min
    // this could be a binary search if you need to care about performance
    const i = freqList.findIndex(el => el[0] >= min);
    if (i === -1) {
        freqList.push([min, max]);
    }
    if (max >= freqList[i][0] || (i !== 0 && min < freqList[i-1][1])) {
        throw new Error('invalid')
    }
    freqList.splice(i, 0, [min, max]);
}

addRange(100, 200)
console.log('ok')
try {
    addRange(0, 101);
} catch(e) {
    console.log('invalid range caught')
}
try {
    addRange(199, 201);
} catch(e) {
    console.log('invalid range caught')
}