graphics/randomizer.js

  1. 'use strict';
  2. /**
  3. * @module Randomizer
  4. */
  5. /**
  6. * Get a random integer between low to high, inclusive.
  7. * If only one parameter is given, a random integer
  8. * from (0, low-1) inclusive.
  9. * @param {number} low - Lower bound on range of random int.
  10. * @param {number} high - Upper bound on range of random int.
  11. * @returns {number} Random number between low and high, inclusive.
  12. */
  13. var nextInt = function(low, high) {
  14. if(typeof high == 'undefined'){
  15. high = low - 1;
  16. low = 0;
  17. }
  18. low = Math.floor(low);
  19. var r = Math.random();
  20. return low + Math.floor(r * (high - low + 1));
  21. };
  22. /**
  23. * Get a random float between low to high, inclusive.
  24. * If only one parameter is given, a random float
  25. * from (0, low-1) inclusive.
  26. * @param {number} low - Lower bound on range of random int.
  27. * @param {number} high - Upper bound on range of random int.
  28. * @returns {number} Random number between low and high, inclusive.
  29. */
  30. var nextFloat = function(low, high) {
  31. if(typeof high == 'undefined'){
  32. high = low;
  33. low = 0;
  34. }
  35. return low + (high - low) * Math.random();
  36. };
  37. /**
  38. * Generates a random number in range (0,255) in hexadecimal.
  39. * @returns {string} Random number in hexadecimal form.
  40. */
  41. var nextHex = function() {
  42. var val = nextInt(0, 255);
  43. if (val < 16) return '0' + val.toString(16);
  44. return val.toString(16);
  45. };
  46. /**
  47. * Generate a random hexadecimal color code of the format #RRGGBB.
  48. * @returns {string} Hexadecimal representation of random color.
  49. */
  50. var nextColor = function() {
  51. var r = nextHex();
  52. var g = nextHex();
  53. var b = nextHex();
  54. return "#" + r + g + b;
  55. };
  56. /**
  57. * Generate a random boolean via fair probability coin toss.
  58. * If `probabilityTrue` is supplied, the coin toss is skewed by that value.
  59. * @param {number} probabilityTrue - Skewed probability of true.
  60. * @returns {boolean} Result of coin flip skewed toward `probabilityTrue`.
  61. */
  62. var nextBoolean = function(probabilityTrue) {
  63. if(typeof probabilityTrue == 'undefined'){
  64. probabilityTrue = 0.5;
  65. }
  66. return Math.random() < probabilityTrue;
  67. };
  68. module.exports = {
  69. nextInt: nextInt,
  70. nextFloat: nextFloat,
  71. nextHex: nextHex,
  72. nextColor: nextColor,
  73. nextBoolean: nextBoolean,
  74. };