weighted mean calculator in typescript

index.ts
/**
 * Calculates the weighted mean of an array of values and an array of weights.
 * @param values - An array of values.
 * @param weights - An array of weights corresponding to the values.
 * @returns The weighted mean of the values.
 */
function weightedMean(values: number[], weights: number[]): number {
  // Check if the arrays are of the same length.
  if (values.length !== weights.length) {
    throw new Error('The values and weights arrays must have the same length.');
  }

  let sumOfWeights = 0;
  let sumOfWeightedValues = 0;

  for (let i = 0; i < values.length; i++) {
    sumOfWeights += weights[i];
    sumOfWeightedValues += values[i] * weights[i];
  }

  return sumOfWeightedValues / sumOfWeights;
}

// Example usage
const values = [1, 2, 3, 4, 5];
const weights = [0.5, 0.5, 1, 1, 2];
const result = weightedMean(values, weights); // 3.3
861 chars
28 lines

In this code, we define a weightedMean function that takes in two arrays of numbers (values and weights) and returns a number (the weighted mean of values). The function first checks if the arrays have the same length using an if statement. If they do not have the same length, an error is thrown.

The function initializes two variables (sumOfWeights and sumOfWeightedValues) to 0. We then loop through each element in values and weights, multiplying the value at the current index in values by the value at the current index in weights. The resulting value is added to sumOfWeightedValues. The value at the current index in weights is added to sumOfWeights.

Finally, we divide the sumOfWeightedValues by the sumOfWeights to get the weighted mean. We then return this value.

gistlibby LogSnag