randomutil.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. define(["util", "whrandom"], function (util, RandomStream) {
  2. var Randomizer = util.Class({
  3. constructor: function (seed) {
  4. this.stream = RandomStream(seed);
  5. },
  6. number: function (max) {
  7. return Math.floor(this.stream() * max);
  8. },
  9. pick: function (seq) {
  10. return seq[this.number(seq.length)];
  11. },
  12. pickDist: function (items) {
  13. var total = 0;
  14. for (var a in items) {
  15. if (! items.hasOwnProperty(a)) {
  16. continue;
  17. }
  18. if (typeof items[a] != "number") {
  19. throw "Bad property: " + a + " not a number";
  20. }
  21. total += items[a];
  22. }
  23. var num = this.number(total);
  24. var last;
  25. for (a in items) {
  26. if (! items.hasOwnProperty(a)) {
  27. continue;
  28. }
  29. last = a;
  30. if (num < items[a]) {
  31. return a;
  32. }
  33. num -= items[a];
  34. }
  35. // FIXME: not sure if this should ever h
  36. return last;
  37. },
  38. string: function (len, chars) {
  39. var s = "";
  40. for (var i=0; i<len; i++) {
  41. s += this.character(chars);
  42. }
  43. return s;
  44. },
  45. character: function (chars) {
  46. chars = chars || this.defaultChars;
  47. return chars.charAt(this.number(chars.length));
  48. }
  49. });
  50. Randomizer.prototype.lower = "abcdefghijklmnopqrstuvwxyz";
  51. Randomizer.prototype.upper = Randomizer.prototype.lower.toUpperCase();
  52. Randomizer.prototype.numberCharacters = "0123456789";
  53. Randomizer.prototype.whitespace = " \t\n";
  54. Randomizer.prototype.punctuation = "~`!@#$%^&*()_-+={}[]|\\;:'\"<>,./?";
  55. Randomizer.prototype.defaultChars =
  56. Randomizer.prototype.lower + Randomizer.prototype.upper +
  57. Randomizer.prototype.numberCharacters + Randomizer.prototype.whitespace +
  58. Randomizer.prototype.punctuation;
  59. return Randomizer;
  60. });