I successfully completed a CodeWars challenge where I wrote the function find_average to calculate the average of numbers in an array. However, I now have some questions:
1) How can I optimize this code in terms of Big-O notation? Is there a way to reduce loop iterations using array.every for input value testing (excluding TypeError when dealing with non-number elements in the array)?
2) I believe that the complexity is currently Θ(n), but am I correct in my assessment?
function find_average(array) {
// your code here
if (Array.isArray(array) && array.every(elem => typeof elem == 'number')) {
const numberCount = array.length;
if (numberCount == 1) {
return array[0];
}
let sum = array.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
})
const averageNumber = sum/numberCount;
return averageNumber;
}
throw new TypeError('Array values are not all numbers.');
}