jeudi 16 juillet 2020

How would you make this more efficient? TheOdinProject [migrated]

Here is my solution to a series of problems in JS fundamentals. I've made it passing but I know this could be more efficient. I'm not looking for anyone to rewrite the code, but just asking what methods should be used when writing similar code in the future. Thanks.

The goal is basically to input two parameters, both have to be positive numbers and typeof numbers otherwise return ERROR. As well form an array that adds said two integers and all numbers between them. So like if you enter 1,4 the answer would compute 1 + 2 + 3 + 4 = 10, and return 10.

const sumAll = function(lowEnd, highEnd) {
    let total = [];
    let sum = 0;
    let first = lowEnd;
    let second = highEnd;
    if (typeof first === 'number' && typeof second === 'number') {
        if (lowEnd >= 0 && highEnd >= 0) {    
            if (lowEnd <= highEnd){
                for (let i = lowEnd; i <= highEnd; i++) {
                    total.push(i);  
                }
            } 
            else {
                for (let i = highEnd; i <= lowEnd; i++) {
                    total.push(i);  
                }
            }
            for (let i = 0; i < total.length; i++) {
                sum += total[i];
            };
            return sum;
        } 
        else if (lowEnd < 0 || highEnd < 0)
            return 'ERROR';
    } 
    else {
        return 'ERROR';
    }
}

and here are the tests,

const sumAll = require('./sumAll')

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

Aucun commentaire:

Enregistrer un commentaire