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