index.ts861 chars28 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