esnext.math.seeded-prng.js 1.4 KB

123456789101112131415161718192021222324252627282930313233
  1. var $ = require('../internals/export');
  2. var anObject = require('../internals/an-object');
  3. var numberIsFinite = require('../internals/number-is-finite');
  4. var createIteratorConstructor = require('../internals/create-iterator-constructor');
  5. var InternalStateModule = require('../internals/internal-state');
  6. var SEEDED_RANDOM = 'Seeded Random';
  7. var SEEDED_RANDOM_GENERATOR = SEEDED_RANDOM + ' Generator';
  8. var setInternalState = InternalStateModule.set;
  9. var getInternalState = InternalStateModule.getterFor(SEEDED_RANDOM_GENERATOR);
  10. var SEED_TYPE_ERROR = 'Math.seededPRNG() argument should have a "seed" field with a finite value.';
  11. var $SeededRandomGenerator = createIteratorConstructor(function SeededRandomGenerator(seed) {
  12. setInternalState(this, {
  13. type: SEEDED_RANDOM_GENERATOR,
  14. seed: seed % 2147483647
  15. });
  16. }, SEEDED_RANDOM, function next() {
  17. var state = getInternalState(this);
  18. var seed = state.seed = (state.seed * 1103515245 + 12345) % 2147483647;
  19. return { value: (seed & 1073741823) / 1073741823, done: false };
  20. });
  21. // `Math.seededPRNG` method
  22. // https://github.com/tc39/proposal-seeded-random
  23. // based on https://github.com/tc39/proposal-seeded-random/blob/78b8258835b57fc2100d076151ab506bc3202ae6/demo.html
  24. $({ target: 'Math', stat: true, forced: true }, {
  25. seededPRNG: function seededPRNG(it) {
  26. var seed = anObject(it).seed;
  27. if (!numberIsFinite(seed)) throw TypeError(SEED_TYPE_ERROR);
  28. return new $SeededRandomGenerator(seed);
  29. }
  30. });