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

320
Visualizações
How to call a function Multiple times

Here is the code snippets

let sum = a => b => b ? sum(a + b) : a;
console.log(sum(10)(20)(3)(4)());

So we are calling the sum function 5 times But let's assume we have an array of any length which contains only numbers

let arrayValue = [1,2,3,4,5,...];

now I want to call the sum function to the length of that array where the last call should be () as it does not contain any number;

Desired Output should be sum(1)(2)(3)(4)(5)() and this will generate programmatically depending on the length of the array

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

0

If you look at

console.log(sum(10)(20)(3)(4)());

It's basically doing this:

const x1 = sum(10);
const x2 = x1(20);
const x3 = x2(3);
const x4 = x3(4);
const x5 = x4();
console.log(x5);

So the question is: How do we do that from this starting point?

let arrayValue = [1,2,3,4,5];

The answer is either a loop or recursion. A loop is simple enough, so let's do that:

let x = sum;
for (const value of arrayValue) {
    x = x(value);
}
x = x();
console.log(x);

let sum = a => b => b ? sum(a + b) : a;

function example(arrayValue) {
    let x = sum;
    for (const value of arrayValue) {
        x = x(value);
    }
    x = x();
    console.log(arrayValue.join(", "), "=>", x);
}

example([10, 20, 3, 4]);
example([1, 2, 3, 4, 5]);

We start by setting x to sum (the function, not a call to it), then for each array value we call whatever function x currently refers to passing in the value and storing the return value back in x again. When we run out of values, we call the result with no argument.

about 4 years ago · Juan Pablo Isaza Relatório

0

You can loop over to the length of the array. You can use .length property to do this and then call your function inside the loop.

Example:

let arrayValue = [1, 2, 3, 4, 5 , …];

for (let i = 0; i < arrayValue.length; i++) {
  someFunction(arrayValue[i]);
}

Reference : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length

I hope this is what you are looking for.

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