Search code examples
javascriptarraystypescriptarray-splice

RangeError: Invalid array length at array spread


I have a rather standard item hydration function that throws "RangeError: Invalid array length". Unfortunately this happens very rarely and in the production so it's hard to catch the input params.

This is the function:

function setProgress(items: SomeType[], id: string, someProperty: string) {
  const index = items.findIndex(item => item.id === id);
  const newItem: SomeType = {...items[index], someProperty };

  return [...items.slice(0, index), newItem, ...items.slice(index + 1); 
}

And this is what is transpiles to (non-uglified):

function setProgress(items, id, someProperty) {
  var index = items.findIndex(function(e) {
      return items.id === id
    }), 
    newItem = Object.assign({}, items[index], {
      someProperty: someProperty
    });
  return items.slice(0, index).concat([newItem], items.slice(index + 1));
}

I've tried playing with different values but I cannot reproduce this error.

Any idea what and how could cause this?


Solution

  • The problem was in an unhandled corner case when the index is -1. Instead of replacing an element, it would double the size of an array. This would eventually lead to stack overflow and hitting the limit of the array size.