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?

4
  • 1
    this SO question may help. It explains Array.apply to fill an array with data efficiently stackoverflow.com/questions/1295584/… Commented Dec 17, 2014 at 22:13
  • This looks fine to me, perfectly readable. Typed arrays don't have .map() anyway. . . Commented Dec 17, 2014 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? Commented Dec 17, 2014 at 22:24
  • @Phil: Typed arrays: developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays Commented Dec 17, 2014 at 22:49

1 Answer 1

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;
    }());
    
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.