random.ts 763 B

123456789101112131415161718
  1. // https://stackoverflow.com/questions/521295/seeding-the-random-number-generator-in-javascript/47593316#47593316
  2. export const LCG = (seed: number) => () =>
  3. ((2 ** 31 - 1) & (seed = Math.imul(48271, seed))) / 2 ** 31;
  4. export function randomSeed() {
  5. return Math.floor(Math.random() * 2 ** 31);
  6. }
  7. // Unfortunately, roughjs doesn't support a seed attribute (https://github.com/pshihn/rough/issues/27).
  8. // We can achieve the same result by overriding the Math.random function with a
  9. // pseudo random generator that supports a random seed and swapping it back after.
  10. export function withCustomMathRandom<T>(seed: number, cb: () => T): T {
  11. const random = Math.random;
  12. Math.random = LCG(seed);
  13. const result = cb();
  14. Math.random = random;
  15. return result;
  16. }