Weighted Average With Input Validation
Compute a weighted mean from value and weight arrays, rejecting length mismatches, non-finite numbers and invalid total weight.
Code
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.lengthshort-circuits the flow with an earlythrowwhen 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
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.