weightedAverage
by alekskorovin
JavaScript
function computeTotalWeightedValue(weights, values) {
var sum = 0;
for (var i=0; i < values.length; i++){
sum += weights[i]*values[i];
}
return sum;
}
function sum(numbers) {
var sum = 0;
for (var index = 0; index < numbers.length; index++) {
sum += numbers[index];
}
return sum;
}
/**
* Compute the weighted average using two number arrays with the same length
* @param {Array} values - an array of values
* @param {Array} weights - an array of weights
* @returns {Number} - return weighted average number
*/
function weightedAverage(values, weights){
// need two arrays of same length
var isNotvalues = !Array.isArray(values),
isNotWeights = !Array.isArray(weights),
valuesLength = values.length,
weightsLength = weights.length,
notTwoArraysOfSameLength = isNotvalues || isNotWeights || valuesLength !== weightsLength;
if (notTwoArraysOfSameLength) {
return undefined;
}
var totalWeight = sum(weights),
totalWeightedValue = computeTotalWeightedValue(weights, values),
totalWeightIsNotZero = totalWeight !== 0,
result;
// checking if we don't divide by zero
if (totalWeightIsNotZero) {
result = totalWeightedValue / totalWeight;
}
return result;
}
console.log(weightedAverage([5, 8], [1, 2]));