Tips for improving the efficiency of the find_average_number(array) simple function?

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.');
}

Answer №1

Instead of iterating twice, once to check if every element is a number and once to add them up, you can optimize by iterating just once. If any element is not a number, you can throw an error immediately:

function calculate_average(array) {
  if (!Array.isArray(array)) {
    throw new TypeError('Values in the array are not numbers.');
  }
  const sum = array.reduce((a, b) => {
    if (typeof b !== 'number') {
      throw new TypeError('Values in the array are not numbers.');
    }
    return a + b;
  }, 0);
  return sum / array.length;
}

function calculate_average(array) {
  if (!Array.isArray(array)) {
    throw new TypeError('Values in the array are not numbers.');
  }
  const sum = array.reduce((a, b) => {
    if (typeof b !== 'number') {
      throw new TypeError('Values in the array are not numbers.');
    }
    return a + b;
  }, 0);
  return sum / array.length;
}

console.log(calculate_average([1, 2, 3]));
console.log(calculate_average([1, 'foo', 3]));

Both this optimized solution and your original implementation have a time complexity of O(n).

Answer №2

To enhance efficiency, you can implement a single loop to first check if the input is an array.

Not only does this method operate in O(n) time complexity, it also outperforms traditional array iteration techniques.

function find_average(array) {
    // your code here
    var sum = 0,
        count = 0,
        i;
  
    if (!Array.isArray(array) || !array.length) return; // or throw error

    for (i = 0; i < array.length; i++) {
        if (typeof array[i] !== 'number') continue;
        sum += array[i];
        count++;
    }
    if (count === 0) return; // or throw error
    return sum / count;
}

console.log(find_average([null, 3, 5, '10', undefined]));
console.log(find_average());
console.log(find_average([]));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A step-by-step guide on transforming an array of objects into an array of arrays with the help of Ramda

I want to convert the following data: [ { a: 2000, b: 4000 }, { a: 8000, b: 5000 }, { a: 6000, b: 1000 } ]; Into this format: [ [ 2000, 8000, 6000 ], [ 4000, 5000, 1000 ] ]; Using Ramda library. I am able to achieve this using R.reduce functio ...

Angular: Modifying the parent scope from a child component

Hey there! So I'm a beginner in this whole programming thing, but I'm currently working on a small application where I can add and update items with details using Ionic, Cordova, and AngularJS. However, I've hit a roadblock with the followin ...

Is it possible for a draggable position:absolute div to shrink once it reaches the edge of a position:relative div

I am facing an issue with draggable divs that have position:absolute set inside a position:relative parent div. The problem occurs when I drag the divs to the edge of the parent container, causing them to shrink in size. I need the draggable divs to mainta ...

Express and Firebase Function: Headers cannot be set once they have already been sent

My experience has been mainly with the Hapi framework for developing RESTful APIs. However, for my current project, I decided to use Express and I'm encountering some confusion regarding the issues that are arising. While testing the POST endpoint us ...

Encountering Uncaught Promise Rejection Warning in Node.js

I can't figure out why I am receiving this error or warning when my code appears to be correct. Below is a snippet of the UserModel that I have been working on: const fs = require('fs'); class UserModel { constructor(filename) { ...

What is the process for loading an HTML form into a specific target using Angular?

Is there a way to load an HTML form into a target in Angular without the use of jQuery? I have a working script, but I am currently stuck on: <html> <head> <script src="components/angular/angular.js"></script> <script&g ...

A comprehensive guide on properly obtaining user details in React with Redux and OIDC

Although I've dabbled in OIDC before, I wouldn't consider myself an expert. Currently, I'm trying to integrate OIDC into a react app using oidc-client-js and redux-oidc libraries, following the redux-oidc-example as a guide. Encountering th ...

What is the proper way to update a dropdown value in a React JS component?

Can you please guide me on how to assign a value in a dropdown in react js? I am retrieving the dropdown data after a delay of 3000 milliseconds and then I need to set a value in the dropdown. const App = ({ children }) => { const val = "ax"; const ...

Using regular expressions to replace strings in JavaScript

I have a URL that resembles the following http://localhost:12472/auctions/auction-12/lots/sort/something/12 I am looking to switch it out with this new URL http://localhost:12472/auctions/auction-12/lots/sort/somethingelse/12 Here, somethingelse can be ...

Joi has decided against incorporating custom operators into their extended features

I am having trouble extending the joi class with custom operators. My goal is to validate MongoDB Ids, but when I try to use the extended object, I encounter the following error: error: uncaughtException: JoiObj.string(...).objectId is not a function TypeE ...

Here's a method for transferring data from one array to another: when there is existing data in the

Although this may seem simple to some, I have been struggling with it for hours without any success. If I have the following data in an array: var tDataValues = { id: "TenantID", text: "FullName", username: "Username", cnic: 'CNIC&ap ...

implementing a delay after hovering over a CSS hover effect before activating it

I'm trying to achieve a specific effect using JavaScript or jQuery, but I'm struggling to figure it out. I have created a simple CSS box with a hover effect that changes the color. What I want is for the hover effect to persist for a set amount o ...

RobotFramework encounters difficulty locating an element using JavaScript

After working with RF for the past few weeks, I came across a persistent issue that has been bothering me. I keep getting the following error: The element with the locator 'XXX' (just a template) cannot be found. Upon investigating the span tha ...

Unleashing the power of JavaScript: A guide to dynamically generating nested arrays

Can you take a look at the code below and help me find the mistake? function pair(str) { // Function to pair specific letters in a string for (var i = 0; i < str.length; i++) { // Check and pair letters based on certain conditions if (s ...

What is the best way to update the state while invoking a component?

Just starting out with react and already hitting a roadblock. I've created an Article Topper component that features a logo, title, and share buttons, which is repeated throughout the site above each article. The issue I'm facing is updating the ...

Error ER_NO_REFERENCED_ROW_2 occurred while attempting to use the function LAST_INSERT_ID

As a newcomer to Vue.js and Express, I've been trying to figure out how to transfer the GuestID from the Guest Table to the foreign key GuestID in my reservations table. app.post('/create',(req,res,next)=>{ var mysql = require(' ...

Implementing dotenv in a Node JS package

I'm in the process of developing a Node application that retrieves search results through a Google Custom Search Engine (CSE). To streamline the process, I plan to extract the component responsible for sending requests to Google and receiving the res ...

JavaScript does not recognize jsPDF

After importing the jsPDF library, I attempted to export to PDF but encountered a JavaScript error stating that jsPDF is not defined. I tried various solutions from similar posts but none of them seemed to work for me. You can find the fiddle here: https ...

"Encountering a mysterious internal server error 500 in Express JS without any apparent issues in

My express.js routes keep giving me an internal server error 500, and I have tried to console log the variables but nothing is showing up. Here are the express routes: submitStar() { this.app.post("/submitstar", async (req, res) => { ...

Unable to replace a value within a two-dimensional array in Python

I'm currently working on a project in Python that involves substituting values within a 2D array. However, I've encountered an issue where the output is not as expected. Instead of getting results like: [0, 0, 0, M] [0, M, 0, 0] [0, 0, 0, 0] [0, ...