javascriptmultidimensional-arrayminmax

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


we have some ranges of frequency in a 2D array. the inner arrays keep frequency upper and lower bounds ,and outer array is a list of sorted ranges:

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

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

new ranges should not overlap saved ones, how can i validate new ones and push them to exact array index?


Solution

  • I think you just need to find the first index such that it's lower number is greater than your lower number. Make sure that your greater number is also lower than it's lower number. Make sure the previous elements greater number is less than your lower number. Then slice it into that index:

    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')
    }