Getting more than 4294967295 objects in an Array

I want to create a 64 bit array, whose limit is endless. But the 32 bit array limits to only 4,294,967,295 objects. I also get an error when I use the push function on an Array with the length 4,294,967,295 : Invalid array length How can I create a 64 bit array?

2 answers

  • answered 2018-10-23 13:18 sumitani

    According to ECMAScript definition this is the maximum length:

    An integer index is a String-valued property key that is a canonical numeric String (see 7.1.16) and whose numeric value is either +0 or a positive integer ≤ 253−1. An array index is an integer index whose numeric value i is in the range +0 ≤ i < 232−1.

    Handling two arrays could be a good idea.

  • answered 2018-10-23 14:06 Adriani6

    It's not possible as you already found out from @Amy and @sumitani. You can however implement your own object or "array container" or array wrapper as you wish.

    I've put up a basic example here:

    var MyArray = function(){
    
      var arr1 = [];
      var arr2 = [];
    
      this.push = function(element){
        if(arr1.length < 4294967296){
            arr1.push(element);
        }else if(arr2.length < 8589934592){
            arr2.push(element);
        }else{
            throw "Invalid array length";
        }
      }
    
      this.get = function(index){
        if(index <= 4294967296){
            return arr1[index];
        }else if(index <= 8589934592){
            return arr2[Math.floor(index / 4294967296)];
        }else{
            throw "Invalid Index";
        }
    
      }
    
      Object.defineProperty(this, 'length', {get: function() {
        return arr1.length + arr2.length;
        }});
    
    };
    
    var arr = new MyArray();
    
    
    for(var i = 0; i < 8589934592; i++){
        arr.push(i);
    }
    
    console.log(arr.get(5));
    
    console.log(arr.length);
    

    So in theory it's possible to have an object to act as an array which is composed of multiple arrays and you just 'calculate' the right index for the right array.

    I say in theory because this method will not work client-side as most browsers have their windows/tabs capped at specific MB/GB memory such as chrome and firefox.

    The limit in Firefox is greater however and that's where I conducted my test.

    The reason I'm giving this answer is because it makes no sense for OP to store such amount of data on the client (I only assume it's client-side) in the first place and it could be useful for hybrid applications (possibly).

    This method can be easily expanded to utilise more space (and memory). There might be better ways of doing it, but that's my quick and dirty 2 cents.