apostrophecms / random-words

Generate one or more common English words. Intended for use as sample text, for example generating random blog posts for testing
MIT License
249 stars 72 forks source link

Optional Global Seeding #49

Open alliefitter opened 6 months ago

alliefitter commented 6 months ago

Allow users to persist an instance of seedrandom across multiple calls to generate().

Is your feature request related to a problem you are experiencing that is not a bug? Please describe.

Using a seed requires you generate the complete list of random words you require in one call to generate(). Each call to generate() returns the exact same set of words, which is clearly how this was intended to work. It could be useful in certain situations to persist the underlying seedrandom instance across multiple calls to generate(). For instance, I have a class that generates example values for a CSV import, of which there will be multiple instances within the same scope. I was expecting to be able to call generate() with a seed from a method on that class, and get a deterministic set of generated words across the entire example CSV. However, I what I ended up with is that every cell in the CSV has the exact same value, as the seed only lives within the scope of generate(). This makes total sense now that I understand how this is intended to work, but persisting the seedrandom instance could be useful in situations like this.

Proposed solution

Describe the solution you'd like

I've got several proposed solutions I'm mulling over, but I've submitted this ticket just ask if this is an enhancement y'all would be interested in. I'll happily submit a PR. The first solution that comes to mind is to just have a variable in the module and a function that sets it. So, there would be let SEED = null, and...

function setSeed(seed: string) {
SEED = seed
}

Then if SEED is set, use that in generate(). I don't particularly love this solution, though. I think what could work better is to have a SEEDS object, also in the module scope. This could map the string seed to an instance of seedrandom. Then, if a flag (maybe preserveSeed) and seed are passed in to generate(), the function could check if that seed already exists in SEEDS, then either use the existing one or create a new one and set it.

Yet another solution could be to allow the caller to pass in an instance of seedrandom. This is probably the simplest I've come up wtih.