Weighted Average With Input Validation

Compute a weighted mean from value and weight arrays, rejecting length mismatches, non-finite numbers and invalid total weight.

JavascriptData Integrity

Code

snippet
export function weightedAverage(values, weights) {
  if (!Array.isArray(values) || !Array.isArray(weights)) {
    throw new TypeError("values and weights must be arrays");
  }
  if (values.length === 0 || values.length !== weights.length) {
    throw new RangeError("values and weights must be non-empty and equal length");
  }
  let weightedSum = 0;
  let totalWeight = 0;
  for (let index = 0; index < values.length; index += 1) {
    const value = values[index];
    const weight = weights[index];
    if (!Number.isFinite(value) || !Number.isFinite(weight)) {
      throw new TypeError("invalid number at index " + index);
    }
    if (weight < 0) throw new RangeError("negative weight at index " + index);
    weightedSum += value * weight;
    totalWeight += weight;
  }
  if (totalWeight === 0) throw new RangeError("total weight must be greater than zero");
  return weightedSum / totalWeight;
}