flat_the_zalupa

ебал в рот считать вложенности
mail@pastecode.io avatar
unknown
javascript
2 months ago
550 B
3
Indexable
Never
function flat3(array, n){
  const stack = array
  const result = []
  let depth = 0
  const stackSizes = [array.length-1]
  while(stack.length){
    pop = stack.pop()
    if (Array.isArray(pop) && depth < n-1 ){
      depth = depth + 1
      stackSizes.push(stackSizes.pop()-1)
      stackSizes.push(pop.length-1)
      stack.push(...pop)
    }else{
      popSize = stackSizes.pop()
      if (popSize ==0){
        depth = depth - 1
      }else{
        stackSizes.push(popSize-1)
      }
      result.push(pop)
    } 
  }
  return result.reverse()
}