Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

277
Vistas
Reducción de una matriz vacía sin valor inicial, cómo ordenar la función con dos parámetros del valor más alto al más bajo

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'); }); });
about 4 years ago · Santiago Gelvez
1 Respuestas
Responde la pregunta

0

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];
about 4 years ago · Santiago Gelvez Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda