random.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. function stringify(obj, replacer, spaces, cycleReplacer) {
  2. return JSON.stringify(obj, serializer(replacer, cycleReplacer), spaces)
  3. }
  4. function serializer(replacer, cycleReplacer) {
  5. var stack = [],
  6. keys = []
  7. if (cycleReplacer == null) cycleReplacer = function(key, value) {
  8. if (stack[0] === value) return "[Circular ~]"
  9. return "[Circular ~." + keys.slice(0, stack.indexOf(value)).join(".") + "]"
  10. }
  11. return function(key, value) {
  12. if (stack.length > 0) {
  13. var thisPos = stack.indexOf(this);
  14. (~thisPos) ? stack.splice(thisPos + 1) : stack.push(this);
  15. (~thisPos) ? keys.splice(thisPos, Infinity, key) : keys.push(key);
  16. if (~stack.indexOf(value)) value = cycleReplacer.call(this, key, value)
  17. } else stack.push(value)
  18. return replacer == null ? value : replacer.call(this, key, value)
  19. }
  20. }
  21. var Mash = function() {
  22. // var n = 0xefc8249d;
  23. var n = 0xbadebabe;
  24. var mash = function(data) {
  25. if (data) {
  26. data = data.toString();
  27. for (var i = 0; i < data.length; i++) {
  28. n += data.charCodeAt(i);
  29. var h = 0.02519603282416938 * n;
  30. n = h >>> 0;
  31. h -= n;
  32. h *= n;
  33. n = h >>> 0;
  34. h -= n;
  35. n += h * 0x100000000; // 2^32
  36. }
  37. return (n >>> 0) * 2.3283064365386963e-10; // 2^-32
  38. } else {
  39. n = 0xbadebabe;
  40. }
  41. };
  42. return mash;
  43. };
  44. var uheprng = function(seed) {
  45. return (function() {
  46. var o = 48; // set the 'order' number of ENTROPY-holding 32-bit values
  47. var c = 1; // init the 'carry' used by the multiply-with-carry (MWC) algorithm
  48. var p = o; // init the 'phase' (max-1) of the intermediate variable pointer
  49. var s = new Array(o); // declare our intermediate variables array
  50. var i; // general purpose local
  51. var j; // general purpose local
  52. var k = 0; // general purpose local
  53. // when our "uheprng" is initially invoked our PRNG state is initialized from the
  54. // browser's own local PRNG. This is okay since although its generator might not
  55. // be wonderful, it's useful for establishing large startup entropy for our usage.
  56. var mash = new Mash(); // get a pointer to our high-performance "Mash" hash
  57. // fill the array with initial mash hash values
  58. for (i = 0; i < o; i++) {
  59. s[i] = mash(Math.random());
  60. }
  61. // this PRIVATE (internal access only) function is the heart of the multiply-with-carry
  62. // (MWC) PRNG algorithm. When called it returns a pseudo-random number in the form of a
  63. // 32-bit JavaScript fraction (0.0 to <1.0) it is a PRIVATE function used by the default
  64. // [0-1] return function, and by the random 'string(n)' function which returns 'n'
  65. // characters from 33 to 126.
  66. var rawprng = function() {
  67. if (++p >= o) {
  68. p = 0;
  69. }
  70. var t = 1768863 * s[p] + c * 2.3283064365386963e-10; // 2^-32
  71. return s[p] = t - (c = t | 0);
  72. };
  73. // this EXPORTED function is the default function returned by this library.
  74. // The values returned are integers in the range from 0 to range-1. We first
  75. // obtain two 32-bit fractions (from rawprng) to synthesize a single high
  76. // resolution 53-bit prng (0 to <1), then we multiply this by the caller's
  77. // "range" param and take the "floor" to return a equally probable integer.
  78. var random = function(range) {
  79. return Math.floor(range * (rawprng() + (rawprng() * 0x200000 | 0) * 1.1102230246251565e-16)); // 2^-53
  80. };
  81. // this EXPORTED function 'string(n)' returns a pseudo-random string of
  82. // 'n' printable characters ranging from chr(33) to chr(126) inclusive.
  83. random.string = function(count) {
  84. var i;
  85. var s = '';
  86. for (i = 0; i < count; i++) {
  87. s += String.fromCharCode(33 + random(94));
  88. }
  89. return s;
  90. };
  91. // this PRIVATE "hash" function is used to evolve the generator's internal
  92. // entropy state. It is also called by the EXPORTED addEntropy() function
  93. // which is used to pour entropy into the PRNG.
  94. var hash = function() {
  95. var args = Array.prototype.slice.call(arguments);
  96. for (i = 0; i < args.length; i++) {
  97. for (j = 0; j < o; j++) {
  98. s[j] -= mash(args[i]);
  99. if (s[j] < 0) {
  100. s[j] += 1;
  101. }
  102. }
  103. }
  104. };
  105. // this EXPORTED "clean string" function removes leading and trailing spaces and non-printing
  106. // control characters, including any embedded carriage-return (CR) and line-feed (LF) characters,
  107. // from any string it is handed. this is also used by the 'hashstring' function (below) to help
  108. // users always obtain the same EFFECTIVE uheprng seeding key.
  109. random.cleanString = function(inStr) {
  110. inStr = inStr.replace(/(^\s*)|(\s*$)/gi, ''); // remove any/all leading spaces
  111. inStr = inStr.replace(/[\x00-\x1F]/gi, ''); // remove any/all control characters
  112. inStr = inStr.replace(/\n /, '\n'); // remove any/all trailing spaces
  113. return inStr; // return the cleaned up result
  114. };
  115. // this EXPORTED "hash string" function hashes the provided character string after first removing
  116. // any leading or trailing spaces and ignoring any embedded carriage returns (CR) or Line Feeds (LF)
  117. random.hashString = function(inStr) {
  118. inStr = random.cleanString(inStr);
  119. mash(inStr); // use the string to evolve the 'mash' state
  120. for (i = 0; i < inStr.length; i++) { // scan through the characters in our string
  121. k = inStr.charCodeAt(i); // get the character code at the location
  122. for (j = 0; j < o; j++) { // "mash" it into the UHEPRNG state
  123. s[j] -= mash(k);
  124. if (s[j] < 0) {
  125. s[j] += 1;
  126. }
  127. }
  128. }
  129. };
  130. // this EXPORTED function allows you to seed the random generator.
  131. random.seed = function(seed) {
  132. if (typeof seed === 'undefined' || seed === null) {
  133. seed = Math.random();
  134. }
  135. if (typeof seed !== 'string') {
  136. seed = stringify(seed, function(key, value) {
  137. if (typeof value === 'function') {
  138. return (value).toString();
  139. }
  140. return value;
  141. });
  142. }
  143. random.initState();
  144. random.hashString(seed);
  145. };
  146. // this handy exported function is used to add entropy to our uheprng at any time
  147. random.addEntropy = function( /* accept zero or more arguments */ ) {
  148. var args = [];
  149. for (i = 0; i < arguments.length; i++) {
  150. args.push(arguments[i]);
  151. }
  152. hash(args.join(''));
  153. };
  154. // if we want to provide a deterministic startup context for our PRNG,
  155. // but without directly setting the internal state variables, this allows
  156. // us to initialize the mash hash and PRNG's internal state before providing
  157. // some hashing input
  158. random.initState = function() {
  159. mash(); // pass a null arg to force mash hash to init
  160. for (i = 0; i < o; i++) {
  161. s[i] = mash(' '); // fill the array with initial mash hash values
  162. }
  163. c = 1; // init our multiply-with-carry carry
  164. p = o; // init our phase
  165. };
  166. // we use this (optional) exported function to signal the JavaScript interpreter
  167. // that we're finished using the "Mash" hash function so that it can free up the
  168. // local "instance variables" is will have been maintaining. It's not strictly
  169. // necessary, of course, but it's good JavaScript citizenship.
  170. random.done = function() {
  171. mash = null;
  172. };
  173. // if we called "uheprng" with a seed value, then execute random.seed() before returning
  174. if (typeof seed !== 'undefined') {
  175. random.seed(seed);
  176. }
  177. // Returns a random integer between 0 (inclusive) and range (exclusive)
  178. random.range = function(range) {
  179. return random(range);
  180. };
  181. // Returns a random float between 0 (inclusive) and 1 (exclusive)
  182. random.random = function() {
  183. return random(Number.MAX_VALUE - 1) / Number.MAX_VALUE;
  184. };
  185. // Returns a random float between min (inclusive) and max (exclusive)
  186. random.floatBetween = function(min, max) {
  187. return random.random() * (max - min) + min;
  188. };
  189. // Returns a random integer between min (inclusive) and max (inclusive)
  190. random.intBetween = function(min, max) {
  191. return Math.floor(random.random() * (max - min + 1)) + min;
  192. };
  193. // when our main outer "uheprng" function is called, after setting up our
  194. // initial variables and entropic state, we return an "instance pointer"
  195. // to the internal anonymous function which can then be used to access
  196. // the uheprng's various exported functions. As with the ".done" function
  197. // above, we should set the returned value to 'null' once we're finished
  198. // using any of these functions.
  199. return random;
  200. }());
  201. };
  202. // Modification for use in node:
  203. uheprng.create = function(seed) {
  204. return new uheprng(seed);
  205. };
  206. module.exports = uheprng;