Sorting a function with two parameters in descending order is possible even when dealing with an empty array and no initial value for reduction

My npm test is not passing the third out of six tests. I have attempted to sort it using the following code snippet:

sumAll.sort(function(min,max)) {
    return max - min;
}
    

However, this approach did not work. I also tried incorporating conditionals in the code using 'if (min > max )... else if ( min < max )', but that didn't work either. I even attempted adding '0' to the reducer variable 'accumulator + currentValue, 0', but I'm still facing issues. Is there a way to sort the sumAll function so that it works properly even when the 'min' argument is higher than the 'max' argument? Any help would be appreciated.

const sumAll = function( min, max ) {
    let fullArr = [];
    let sum = 0; 

    const reducer = (accumulator, currentValue) => accumulator + currentValue; 

    // let highestToLowest =

    for ( let i = min; i <= max; i++) {
        fullArr.push(i);
    }

    // sumAll.sort(function(min,max)) {
    //     return max - min;
    // }
        
    // // let lowestToHighest = fullArr.sort((a, b) => a - b);
    // let highestToLowest = fullArr.sort((min, max) => max-min);

    sum = fullArr.reduce(reducer);

    return sum;
}

sumAll(1,4);
sumAll(123, 1);        <----------  I failed on this function call saying it 'Reduce 
                                    of empty array with no initial value.... 

---------------------------- Jest code --------------------------

const sumAll = require('./sumAll')

describe('sumAll', () => {
  test('sums numbers within the range', () => {
    expect(sumAll(1, 4)).toEqual(10);
  });
  test('works with large numbers', () => {
    expect(sumAll(1, 4000)).toEqual(8002000);
  });
  test('works with larger number first', () => {
    expect(sumAll(123, 1)).toEqual(7626);
  });
  test.skip('returns ERROR with negative numbers', () => {
    expect(sumAll(-10, 4)).toEqual('ERROR');
  });
  test.skip('returns ERROR with non-number parameters', () => {
    expect(sumAll(10, "90")).toEqual('ERROR');
  });
  test.skip('returns ERROR with non-number parameters', () => {
    expect(sumAll(10, [90, 1])).toEqual('ERROR');
  });
});

Answer №1

The following code snippet demonstrates how to use a reducer to sum array values:

arr.reduce((ac, cv) => ac + cv, 0);

To prevent errors, it is important to add an initial value when working with an empty array:

In my experience, the code below has worked well for me:

const sumAll = function( min, max ) {
    let fullArr = [];
    let sum = 0; 

    for ( let i = min; i <= max; i++) {
        fullArr.push(i);
    }

    sum = fullArr.reduce((ac, cv) => ac + cv, 0);

    return sum;
}

console.log(sumAll(1,4));
console.log(sumAll(123,1));
// Output 10
// Output 0 (because min < max)

If you want sumAll(123, 1) to print 7626, remember to switch both min and max when min > max

One way to achieve this is by using the following for loop:

    for ( let i = (min <= max ? min : max); i <= (max >= min ? max : min); i++) { }

Alternatively, as suggested by @adiga:

if( min > max) [min, max] = [max, min];

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

What value does a variable have by default when assigned to the ko.observable() function?

I am in the process of learning KnockoutJS and I have implemented code for folder navigation in a webmail client. In the view code, there is a comparison being made to check if the reference variable $data and $root.chosenFolderId() point to the same memor ...

Don't worry about Higher Order Components while conducting tests on React Components

Currently, I am attempting to test a straightforward Material UI select form that utilizes a FormControl and is exported with withStyles. In my testing scenario, the goal is quite simple: I wish to confirm that my component appropriately renders a child el ...

Utilize an external JavaScript file function within an AngularJS controller

I have an external JavaScript file with additional functions that I am trying to call from an Angular controller. Here is an example of the external.js file: ... ... function fun() { ... ... } ... ... The controller in question is called acccountCon ...

Encountering a Problem with Image Rendering in Next.js

Issue: I am facing a problem while trying to display a react component using <Gallery images={images} />. The component itself is rendered, but the images from the array are not showing up initially. However, when I resize the screen by dragging the ...

What is the best way to set up a React handler that can handle multiple values effectively?

Struggling with a handler that is not behaving as expected. I need to update the 'quantity' value of multiple items, but currently they all get updated with the last value entered. How can I change multiple values and update items individually? H ...

Is there a way to access and invoke a exposed function of a Vue component within a default slot?

Exploring the realms of a vue playground. The functions interfaceFunction in both ChildA and ChildB are exposed. In App, these functions can be called by obtaining references to the components that expose them. This allows direct function calls from with ...

Use jQuery to refresh the jQuery sparkline chart after fetching data asynchronously

Background Utilizing the jquery.sparkline library to generate Pie Charts. The data for these charts is stored in an array. Upon initial page load, a web-service call is made (using .ajax) to fetch the data. The callback function associated with this call ...

Encountering a JSDOM error of "ECONNREFUSED 127.0.0.1:80" during test execution on Azure DevOps

While running the job on Azure DevOps with yarn test:unit, I encounter a repeating error multiple times. However, this error does not seem to affect the passing of tests. The project utilizes vue and jest for testing purposes. Interestingly, when running t ...

The custom attribute in jQuery does not seem to be functioning properly when used with the

I am currently working with a select type that includes custom attributes in the option tags. While I am able to retrieve the value, I am experiencing difficulty accessing the value of the custom attribute. Check out this Jsfiddle for reference: JSFIDDLE ...

Beneath the Surface: Exploring Visual Studio with NPM and Typescript

Can you explain how Visual Studio (2015) interacts with external tools such as NPM and the Typescript compiler (tsc.exe)? I imagine that during the building of a solution or project, MSBuild is prompted to execute these additional tools. I'm curious a ...

Page Not Found: React and Express Route Not Found

I encountered an error while attempting to use the sign-up route: POST http://localhost:3001/sign-up 404 (Not Found). I searched for similar issues on StackOverflow but couldn't pinpoint the source of my problem... In the frontend, I am fetching the ...

Retrieving a attribute from an element on a separate webpage

On my website, I have a list of links that use ajax to load new pages. Each of these new pages features a gallery of images with a main image. I am trying to figure out how to extract the source URL from the main image in order to display it as a thumbn ...

Increase the placeholder's line height and font size for the InputBase component in Material UI

Hello, I am new to material UI and currently using it for my website development. I am trying to customize the placeholder of the inputbase in material ui by increasing their lineHeight and fontSize. However, I am having trouble accessing the placeholder A ...

Ways to remove items from Vuex store by utilizing a dynamic path as payload for a mutation

I am looking to implement a mutation in Vuex that dynamically updates the state by specifying a path to the object from which I want to remove an element, along with the key of the element. Triggering the action deleteOption(path, key) { this.$store.d ...

Angular 6: Dealing with Type Errors in the HttpClient Request

I am encountering issues with my services. I am attempting to retrieve a list of media files (generated by NodeJS, which generates a JSON file containing all media items). Although I can successfully fetch the data, I am facing an error stating "Property & ...

Creating an array of form input names using JavaScript within the HTML input tag

I have a two part question that I'm hoping someone can help me with. There was a similar question asked recently that included information about this particular type of array in PHP, but unfortunately, I can't seem to locate it at the moment. 1. ...

Whenever I attempt to run 'npm run build', I consistently encounter an error

I'm currently in the process of creating a website using React and Next.js. All my files are uploaded to a hosting platform, and I've successfully connected to it via SSH. However, when attempting to run the command 'npm run build', I e ...

React - Struggling to render an image received as a prop within a React component

Just starting out with React. I'm trying to figure out how to properly display an image from the props of my CheckoutProduct component inside an image HTML tag. Image displaying the Product item but failing to do so. Here's the code snippet: i ...

Issue encountered while attempting to install gatsby-cli: npm ERROR! Unable to execute node-gyp-build due to permission denial

Attempting to install gatsby-cli on WLS2 using npm resulted in failure. Below is the error message received: root@LAPTOP-7EEFPLOM:~# npm install -g gatsby-cli npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail=" ...

Tips on leaving comments inside a render <div>

Hey there! I'm facing an unusual issue in my React+Webpack project. Even though I marked a line as a comment using //, it still gets rendered in the HTML output. Strangely, I have never encountered this problem before and can't figure out what tr ...