Skip to content

feat: implement array.pushArray to fix "Maximum call stack size exceeded" in array.push #40025

@milahu

Description

@milahu

Is your feature request related to a problem? Please describe.

in the wild, there exists this pattern to push elements from a source array to a destination array

destinationArray.push(...sourceArray) // ... = spread operator

this pattern is used cos its fast, faster than dst = dst.concat(src)
and cos its short, shorter than for (let i = 0; i < src.length; i++) dst.push(src[i])

but the source array is limited by the Maximum call stack size of around 100K in nodejs and 500K in firefox

// problem
[].push(...Array.from({ length: 1000*1000 }))
// Uncaught RangeError: Maximum call stack size exceeded

Describe the solution you'd like

destinationArray.pushArray(sourceArray)
// array.pushArray polyfill in typescript
(Array.prototype as any).pushArray = function pushArray(...otherList: any[]) {
  let c = 0; // count pushed elements
  for (let a = 0; a < otherList.length; a++) {
    const other = otherList[a];
    for (let i = 0; i < other.length; i++) {
      this.push(other[i]);
      c++;
    }
  }
  return c;
};

(someArray as any).pushArray(otherArray1, otherArray2, [otherItem])

Describe alternatives you've considered
using a library, but imho this should be a core feature

related

sample use case + code transformer sveltejs/svelte#6716
the code transformer could be implemented in eslint

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions