xor128.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // A Javascript implementaion of the "xor128" prng algorithm by
  2. // George Marsaglia. See http://www.jstatsoft.org/v08/i14/paper
  3. (function(global, module, define) {
  4. function XorGen(seed) {
  5. var me = this, strseed = '';
  6. me.x = 0;
  7. me.y = 0;
  8. me.z = 0;
  9. me.w = 0;
  10. // Set up generator function.
  11. me.next = function() {
  12. var t = me.x ^ (me.x << 11);
  13. me.x = me.y;
  14. me.y = me.z;
  15. me.z = me.w;
  16. return me.w ^= (me.w >>> 19) ^ t ^ (t >>> 8);
  17. };
  18. if (seed === (seed | 0)) {
  19. // Integer seed.
  20. me.x = seed;
  21. } else {
  22. // String seed.
  23. strseed += seed;
  24. }
  25. // Mix in string seed, then discard an initial batch of 64 values.
  26. for (var k = 0; k < strseed.length + 64; k++) {
  27. me.x ^= strseed.charCodeAt(k) | 0;
  28. me.next();
  29. }
  30. }
  31. function copy(f, t) {
  32. t.x = f.x;
  33. t.y = f.y;
  34. t.z = f.z;
  35. t.w = f.w;
  36. return t;
  37. }
  38. function impl(seed, opts) {
  39. var xg = new XorGen(seed),
  40. state = opts && opts.state,
  41. prng = function() { return (xg.next() >>> 0) / 0x100000000; };
  42. prng.double = function() {
  43. do {
  44. var top = xg.next() >>> 11,
  45. bot = (xg.next() >>> 0) / 0x100000000,
  46. result = (top + bot) / (1 << 21);
  47. } while (result === 0);
  48. return result;
  49. };
  50. prng.int32 = xg.next;
  51. prng.quick = prng;
  52. if (state) {
  53. if (typeof(state) == 'object') copy(state, xg);
  54. prng.state = function() { return copy(xg, {}); }
  55. }
  56. return prng;
  57. }
  58. if (module && module.exports) {
  59. module.exports = impl;
  60. } else if (define && define.amd) {
  61. define(function() { return impl; });
  62. } else {
  63. this.xor128 = impl;
  64. }
  65. })(
  66. this,
  67. (typeof module) == 'object' && module, // present in node.js
  68. (typeof define) == 'function' && define // present with an AMD loader
  69. );