import { assert } from "../../assert.js";

/**
 * @template T
 * @param {T[]} array
 * @param {function(el:T, index:number):number} scoreFunction
 * @returns {T[]}
 */
export function array_pick_best_elements(array, scoreFunction) {
    assert.notEqual(array, undefined, 'array is undefined');
    assert.isArray(array, 'array');

    assert.isFunction(scoreFunction, 'scoreFunction');

    let bestScore;

    const size = array.length;

    if (size === 0) {
        return [];
    }

    const first = array[0];

    bestScore = scoreFunction(first, 0);

    assert.isNumber(bestScore, 'bestScore');

    const result = [first];

    for (let i = 1; i < size; i++) {
        const el = array[i];

        // compute score
        const score = scoreFunction(el, i);

        assert.isNumber(score, 'score');

        if (score > bestScore) {
            bestScore = score;

            result.splice(0, result.length);

            result.push(el);
        } else if (score === bestScore) {
            result.push(el);
        }
    }

    return result;
}
