Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

282
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda