簡體   English   中英

減少沒有初始值的空數組,如何對具有兩個參數的函數從最大值到最小值進行排序

[英]Reduce of empty array with no initial value, how to sort function with two parameters from highest to lowest value

我正在為我的代碼運行 npm 測試,但在六次測試中的第三次測試失敗。 我嘗試使用以下內容對其進行排序:

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

但它不起作用。 我嘗試使用 'if (min > max)... else if ( min < max )' 在代碼中添加條件,但它仍然不起作用。 我嘗試在減速器變量 'accumulator + currentValue, 0' 上添加 '0' 但仍然無法正常工作。 有什么方法可以對 sumAll 函數進行排序,即使它使用比“max”參數更高的“min”參數,它仍然可以工作? 請幫忙。

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.... 

---------------------------------------- 笑話代碼 -------------------- ------

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

對數組值求和的減速器是:

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

添加初始值應防止錯誤: empty array with no initial value

這段代碼對我有用:

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)

如果你想sumAll(123, 1)打印7626你必須在min > max時切換minmax

例如,使用這個for循環:

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

或如@adiga 建議的那樣:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM