Estoy ejecutando la prueba npm para mi código y estoy fallando en la tercera prueba de seis pruebas. He intentado ordenarlo con lo siguiente:
sumAll.sort(function(min,max)) { return max - min; }Pero no está funcionando. Traté de agregar condicionales en el código usando 'if (min > max)... else if (min <max)' pero tampoco funciona. Intenté agregar '0' en la variable reductora 'accumulator + currentValue, 0' pero aún no funciona. ¿Hay alguna forma de ordenar la función sumAll para que siga funcionando incluso si usa argumentos 'min' más altos que el argumento 'max'? Por favor ayuda.
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....---------------------------- Código de broma -------------------- ------
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'); }); });El reductor para sumar el valor de la matriz es:
arr.reduce((ac, cv) => ac + cv, 0); Agregar un valor inicial debería evitar el error: empty array with no initial value
Este código funciona para mí:
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) Si desea que sumAll(123, 1) imprima 7626 , debe cambiar min y max cuando min > max
Por ejemplo, use esto for bucle:
for ( let i = (min <= max ? min : max); i <= (max >= min ? max : min); i++) { }o como lo sugiere @adiga:
if( min > max) [min, max] = [max, min];