DEV Community

Discussion on: How many ways iterate the objects and arrays in javascript?

Collapse
 
qm3ster profile image
Mihail Malo • Edited

Here's one more that doesn't overflow stack :)

const recursiveArrayHandling = (array, i = array.length) => {
  const item = array[--i]
  if (i % 4000) return recursiveArrayHandling(array, i)
  console.log(i, item)
  if (i) return setTimeout(recursiveArrayHandling, 0, array, i)
}
recursiveArrayHandling(new Array(1024 ** 3))

It's full of dumb hacks though, in real life I'd do this:

const recursiveArrayHandling = (array, fn) => {
  const { length } = array
  const innerFunc = (arr, i = 0) => {
    if (i === length) return
    arr[i] = fn(arr[i])
    if (i % 0x80) return innerFunc(arr, i + 1)
    if (i % 0x8000) console.log(i, arr[i]) // TODO: remove
    return setTimeout(innerFunc, 0, arr, i + 1)
  }
  innerFunc(array)
}

recursiveArrayHandling(new Array(1024 ** 3), x => x)

Why only 0x80? To have a lot of headroom, in case the fn is also something recursive.

The real problem here is that a 1024**3 array will quickly use up your memory, even if you start filling it with 0, undefined or even pointers to the same object. It can only exist as sparse.