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

134
Vistas
Return each array item incrementally with each function call when passed as callback

I have an array of objects like: [{}, {}, {}, {}, {}]; I also have a function that is recursive and accepts a function as a parameter:

function recursiveFunction(getResponse) {
   const result = getResponse();
   
   const conditionMet = check(result);

   if(conditionMet) {
      return result;
   }

   return recursiveFunction(getResponse);
} 

How can I create a function getResponse so each time that it is called in recursiveFunction it will return the next iteration of my array?

For example upon each recursion it should be getting the next object in the array:

function getResponse(index) {
   return array[index ++];
}

And when I call it:

const firstIndex = -1; // Because index ++ in function
const result = recursiveFunction(getResponse(firstIndex));

I understand why it is only returning the first value but I'm not sure how I can modify it to return the next index in the array when calling it again.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

The way to do this in JavaScript would be to use the built-in Iteration Protocol -

const myinput =
  [ {a:1}, {b:2}, {c:3}, {d:4} ]
  
const it =
  myinput.values()
  
console.log(it.next())
console.log(it.next())
console.log(it.next())
console.log(it.next())
console.log(it.next())

{value: {a:1}, done: false}
{value: {b:2}, done: false}
{value: {c:3}, done: false}
{value: {d:4}, done: false}
{value: undefined, done: true}

You could make your own iter function which returns a function like the one you describe -

  
function iter(iterable) {
  const it = iterable.values()
  return () => it.next().value
}

const inputA = [1,2,3]
const inputB = ["a","b","c"]

const nextA = iter(inputA)
const nextB = iter(inputB)

console.log(nextA()) // 1
console.log(nextA()) // 2
console.log(nextB()) // "a"
console.log(nextB()) // "b'
console.log(nextA()) // 3
console.log(nextB()) // "c"
console.log(nextA()) // undefined
console.log(nextB()) // undefined

In your program, you will have to check for undefined to know when there are no values left -

function recursiveCheck(check, getResponse) {
  const result = getResponse()
  if (result === undefined)
    return "not found"
  else if (check(result))
    return "condition met"
  else
    return recursiveCheck(check, getResponse)
}

const output = recursiveCheck(myChcek, iter([{...}, {...}, ...]))

console.log(output)

Using recursion in this particular cases means you the size of your input will be limited. If you simply use for..of all of your problems go away -

function iterativeCheck(check, iterable) {
  for (const result of iterable)
    if (check(result))
      return "condition met"
  return "not found"
}

const output = iterativeCheck(myCheck, [{...}, {...}, {...}, ...])

console.log(output)

See also Symbol.asyncIterator for how this approach can be used on async iterables.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You should be passing the function as the argument, not calling the function.

const result = recursiveFunction(getResponse);

Also, if you initialize the index as -1, you need to use ++index, not index++.

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