UNPKG

@woosh/meep-engine

Version:

Pure JavaScript game engine. Fully featured and production ready.

46 lines (33 loc) 1.16 kB
import { assert } from "../../assert.js"; /** * Picks element with highest score from the array using supplied scoring function. * If multiple elements with the same highest score exist, the result will be first such encountered element * @template T * @param {T[]} array * @param {function(el:T, index:number):number} scoreFunction * @returns {T|undefined} */ export function array_pick_best_element(array, scoreFunction) { assert.notEqual(array, undefined, 'array is undefined'); assert.isFunction(scoreFunction, 'scoreFunction'); let bestElement; let bestScore; const size = array.length; if (size === 0) { return undefined; } bestElement = array[0]; bestScore = scoreFunction(bestElement, 0); assert.isNumber(bestScore, 'bestScore'); 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; bestElement = el; } } return bestElement; }