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

javascriptsnippet
22 lines
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;
}

What the code does

The working surface is the function weightedAverage — everything else is wiring.

Iteration happens inside for (let index = 0; index < values.length; index += 1) — everything outside it runs once. Invalid states are rejected up front: it throws TypeError and RangeError instead of continuing with bad data.

What to watch for

  • The guard values.length === 0 || values.length !== weights.length short-circuits the flow with an early throw when its condition holds.

Using it

The primary signature is export function weightedAverage(values, weights)

weightedAverage is what another module would consume; nothing else here is load-bearing for callers.

Key statements

if (totalWeight === 0) throw new RangeError("total weight must be greater than zero");
throw new RangeError("values and weights must be non-empty and equal length");
if (weight < 0) throw new RangeError("negative weight at index " + index);

Interactive Tools for This Topic

FAQ

Is there a failure path for bad input?
It throws `TypeError` and `RangeError` before any real work runs, via the guard `values.length === 0 || values.length !== weights.length` — handle it at the call site or let it propagate deliberately.
What has to be installed first?
Nothing — the runtime itself provides everything the code touches. The file defines `weightedAverage` at load time.