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

139
Visualizações
The elegant way to resolve negative zero in Javascript

I have to multiply the sign of all elements in an array.

For example 1:

input: [1, 2, 3]
output: 1
Explain: 1 * 1 * 1 = 1

Ex2:

input: [1, -2, 3]
output: -1
Explain: 1 * (-1) * 1 = -1

Ex3:

input: [1, -2, 3, 0]
output: 0
Explain: 1 * (-1) * 1 * 0 = 0

And here is my solution

function cal(A)
{
    return A.reduce((total, currentValue) => total * Math.sign(currentValue), 1);
}

However, the output of ex3 cal([1, -2, 3, 0]) is -0.

I've already thought about adding one more condition like this

function cal(A)
{
    var total = A.reduce((total, currentValue) => total * Math.sign(currentValue), 1);
    if(total === 0)
        return 0;
    else
        return total;
}

And obviously, It looks ugly. Is there a more elegant way to resolve that?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

In order to avoid conditional checks and keep the function purely computational you can use the curious rules of -0 to simply add 0 to the result of your reduce() which will have no effect on non-zero results but will have the effect of converting -0 to 0.

function cal(arr) {
  return arr.reduce((a, c) => a * Math.sign(c), 1) + 0;
}

console.log(cal([1, 2, 3]));     // 1
console.log(cal([1, -2, 3]));    // -1
console.log(cal([1, -2, 3, 0])); // 0

See signed zero for more general discussion.

about 4 years ago · Juan Pablo Isaza Relatório

0

In your example, there is no need to multiply all the values. If there is at least one zero, the result is zero, so there is no need to iterate through the entire array. Example below:

function compute(arr)
{
    let result = true;
    for (let item of arr) {
        if (item === 0) return 0;
        if (item < 0) result = !result;
    }
    return result ? 1 : -1;
}

console.log(compute([1, 2, 3]));
console.log(compute([1, -2, 3]));
console.log(compute([1, -2, 3, 0]));

about 4 years ago · Juan Pablo Isaza 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