Best way to populate javascript array

I am trying to find the best way to populate an array using JavaScript.

I currently have a function that looks like this to generate a fixed sized array of sampled data. I need the sample data to be non-uniform (non-uniform) and preferably pseudo-random.

function () {
    var arraySize = (1024 * 10) / 4;  // Get size for 10k buffer

    var testdata = new Uint32Array(arraySize);

    for (var i = 0; i < arraySize; i++) {
        testdata[i] = Math.random() * 0xFFFFFFFF;
    };

    //...
};

      

And it works, but I suspect it's not very idiomatic for JavaScript.

My broader problem is that I will need larger (and larger!) Arrays for the tests I run, so I am concerned about saturating the system with another temporary object.

Is there a more efficient / idiomatic approach to populating an array?

+3


source to share


1 answer


Your method is beautiful and very clear.

Perhaps more idiomatic, or at least concise approaches to EcmaScript 6:



  • TypedArray.from

    :

    Uint32Array.from( {length: 1024 * 10 / 4 /* 10k buffer */}, function() {
        return Math.random() * 0xFFFFFFFF;
    })
    // Alternatively, with an arrow function as a one-liner:
    Uint32Array.from( {length: 2560 }, () => Math.random() * 0xFFFFFFFF );
    
          

  • An immediately invoked generator expression (IIGE) to create an iterator on demand:

    new Uint32Array(function*() {
        var arraySize = (1024 * 10) / 4;  // Get size for 10k buffer
        for (var i=0; i<arraySize; i++)
            yield Math.random() * 0xFFFFFFFF;
    }());
    
          

+2


source







All Articles