loading...

Random Seeds, Lodash, and ES6 Imports

petecorey profile image Pete Corey Originally published at petecorey.com on ・2 min read

David Bau’s seedrandom Javascript library is an excellent tool for introducing deterministic random values into your Javascript project. After setting a fixed seed, Math.random will produce a stream of random values. Those same random values will be produced again, in order, the next time you run your program. This is very important when creating generative art or procedurally generated game content.

However, there’s a small problem when trying to combine seedrandom with a library like Lodash. Ideally, we’d like Lodash to respect our random seed, so methods like shuffle would always produce a deterministic shuffling. Unfortunately, with a setup like the one described below, this won’t be the case:


import _ from "lodash";
import seedrandom from "seedrandom";

seedrandom("seed", { global: true });

_.shuffle([1, 2, 3]); // Ignores our random seed.

The seedrandom library wholesale replaces Math.random with a new pseudo-random number generator. Because we’re importing lodash before we initialize seedrandom, Lodash defines all of its functions, shuffle included, to use the original reference to Math.random. We need to initialize seedrandom before importing Lodash.

Unfortunately, this won’t work:


import seedrandom from "seedrandom";
seedrandom("seed", { global: true });

import _ from "lodash";

Node.js requires all import statements to be at the top of a module. We can’t initialize seedrandom before importing Lodash.

Thankfully, a simple solution exists. We’ll make a new module called seed.js that simply imports seedrandom and then initializes it with our seed:


import seedrandom from "seedrandom";

seedrandom("seed", { global: true });

Next we can import our local "./seed.js" module before importing Lodash:


import "./seed.js";
import _ from "lodash";

_.shuffle([1, 2, 3]); // Produces deterministic shufflings!

And with that small change seedrandom, Lodash, and ES6-style imports all play nicely together. Our shuffle function will now product deterministic shufflings based on the seed we pass into seedrandom!

Posted on by:

Discussion

markdown guide