import { min2 } from "../../../core/math/min2.js";

/**
 * Given a column of ordered values in increasing order, returns low index of matching value
 * @param {RowFirstTable} table
 * @param {number} time
 * @param {number} [column_index]
 * @return {number}
 */
export function table_find_min_index_in_ordered_column(table, time, column_index = 0) {
    let minIndex = 0;
    let maxIndex = table.length - 1;

    while (minIndex <= maxIndex) {

        // low midpoint, this is essentially Math.floor( (minIndex + maxIndex) / 2 )
        const pivotIndex = (minIndex + maxIndex) >>> 1;

        const cmp = time - table.readCellValue(pivotIndex, column_index);

        if (cmp > 0) {
            minIndex = pivotIndex + 1;
        } else if (cmp < 0) {
            maxIndex = pivotIndex - 1;
        } else {
            // exactly on the pivot sample
            return pivotIndex;
        }
    }

    return min2(minIndex, maxIndex);
}