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

Discovering the world of Javascript and JQuery by diving into the intricacies of

Similar Question: Formatting dates using Javascript I have recently started working with JavaScript and jQuery. I am currently experimenting with creating a page that retrieves data from a public Google calendar and displays the events, including star ...

Ways to retrieve data object within an HTMLElement without relying on jQuery

Within my web application, I have successfully linked a jQuery keyboard to a textbox. Now, I am seeking a way to explicitly call the keyboard.close() function on the keyboard as I am removing all eventListeners from the text field early on. To achieve thi ...

You cannot make a hook call within the body of a function component, unless you are using useNavigate and useEffect in conjunction with axios interceptors

Currently, I am delving into React and attempting to include a Bearer token for private API calls. My approach involves writing a private axios function to intercept requests and responses. Subsequently, I invoke it in my API.js file to fetch data from the ...

error in assetic:watch - unserialize(): Offset error detected

While working on my project using everyday assetic in work (OS: Win7), I encountered an error today when I ran the command: php bin/console assetic:watch. The error message I received was: [Symfony\Component\Debug\Exception\ContextEr ...

Guide on programmatically redirecting a user to a different route

I am currently working on a VueJS 3 application using Quasar, and I am facing difficulties with programmatically utilizing the Router. The issue can be summarized as follows: 1. The Challenge When attempting to navigate the User to a different route, onl ...

A step-by-step guide on conducting an npm audit for global packages

According to the official npm documentation, you can manually execute npm audit on locally installed packages, which require both a package.json and a package-lock.json file. Global packages do not have a package-lock.json. If you try to audit them, it wi ...

fullpage.js: the content exceeds the height limit

I am currently working on customizing the jquery script fullpage.js for a website built on the French CMS "SPIP" (). This script is used to create a one-page website with both horizontal and vertical navigation. However, I have encountered an issue with ...

What is the process for displaying every version of an npm package?

To view all the versions of a node module [webpack], I ran the following command in the windows command prompt: npm view webpack versions However, this command only shows the first 100 versions and then displays "331 more" text. Any suggestions on how I ...

Unable to execute postinstall in the working directory %s %s (current working directory=%s)

Warning: npm lifecycle [email protected]~postinstall script could not be executed in the specified directory %s %s (directory=%s) [email protected]. Please make sure to run gulp check.versions, gulp build.bundle.rxjs, npm prune, gulp webdriver, ...

Display or conceal a div depending on the selected radio button

I am attempting to display a hidden div based on the input of a radio button. If the "yes" option is checked, the hidden div should be shown. Conversely, if the "no" option is checked, the div should be hidden. I'm not sure why this code isn't w ...

Validation of Selenium in the Node.js Environment

I have a block of code that is meant to verify if an element exists on the page and display a message accordingly. However, I am struggling to correctly check my elements. Should I use an object or an array for this task? And how can I check multiple value ...

Boost the delay in the transition speed for hiding the Navbar while scrolling down with the help of Bootstrap

Hi there! I am currently learning HTML, CSS, and JS. I'm working on a homepage project using Bootstrap-5 and have successfully integrated a navbar. However, I've noticed that the navbar disappears too quickly when I scroll down. Is there a way to ...

Executing react scripts through the frontend-maven-plugin is ineffective

I have a main Maven project that includes a separate frontend project within it. When I navigate to the frontend folder using cmd and execute "npm run build", everything works correctly. However, when I run "mvn clean install -PautoInstallPackage" from t ...

It is not possible to invoke a function within the AJAX success method

When trying to display an error message in my notify (toast) div using jQuery in Ajax success, I am encountering difficulties. Despite decoding the response from the URL properly, only .show() and .hide() functions seem to work. Although I have used conso ...

"Troubleshooting: Why is the onError event not triggering

Has anyone else experienced issues with using a third-party API to fetch YouTube thumbnails with higher resolution, sometimes resulting in a code 404 error? I've been trying to replace the image source with a default YouTube thumbnail retrieved from i ...

Encountering a problem during the setup of Vue.js with Onsen UI

Looking to dive into onsenUI vue but running into some issues. When I try to start a new project with monaca using the command: monaca create helloworld and choosing the onsenui-v2-vue-splitter template, I encounter the following error: npm WARN package ...

The AnimationMixer is refusing to start playing the animation from the gltf file

I have successfully imported a model using three.js and it works fine. Now, I am trying to run animations from a GLB file. Although I can retrieve the animation names with three.js, the TJS library fails to play my animations. GLB FILE There are two anim ...

Retrieve JSON data from PHP using D3.request

Looking to extract data from an SQL database using PHP and then convert it into JSON format with the "echo json_encode($array);" function. I have a requirement to create a graph using D3.js, which means I need to transfer this JSON data from PHP. Can anyo ...

Is it possible to share a variable between different scopes in an Angular environment?

As I dive into building my first real Angular.js application, focused on assisting judges during courtroom hearings, I am encountering various challenges and learning how to overcome them. The application consists of views such as Calendar, Documents, and ...

Using the inline calendar feature of Bootstrap 3 Datepicker to easily select and capture dates

I've been struggling to extract the selected date from my bootstrap 3 datepicker, and despite attempting to follow the documentation, I still can't grasp it. Here's what I tried: <div id="datetimepicker"> <i ...