3

I'm trying to find a better way to fill an array using JavaScript.

Currently I have a function that looks like this to generate a fixed size array of sample data. I need the sample data to be not the same (non-homogenous) 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 concern is that for the tests I'm running, I'm going to need larger (and larger!) arrays so I'm concerned about saturating the system for an otherwise temporary object.

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

  • 1
    this SO question may help. It explains Array.apply to fill an array with data efficiently http://stackoverflow.com/questions/1295584/most-efficient-way-to-create-a-zero-filled-javascript-array – Andrew Lohr Dec 17 '14 at 22:13
  • This looks fine to me, perfectly readable. Typed arrays don't have `.map()` anyway. . . – reptilicus Dec 17 '14 at 22:22
  • I confused as to why he can't just place the `for loop` to run 10k times? What is the `arraySize` and `Uint32Array` call for? – Phil Dec 17 '14 at 22:24
  • @Phil: Typed arrays: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays – Felix Kling Dec 17 '14 at 22:49

1 Answers1

2

Your method is fine and very understandable.

Maybe more idiomatic, or at least concise, approaches come with 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;
    }());
    
Bergi
  • 630,263
  • 148
  • 957
  • 1,375