esnext.math.seeded-prng.js 1.6 KB

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