You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

RandomUtil.js 1.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /**
  2. * @const
  3. */
  4. var ALPHANUM = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  5. /**
  6. * Generates random int within the range [min, max]
  7. * @param min the minimum value for the generated number
  8. * @param max the maximum value for the generated number
  9. * @returns random int number
  10. */
  11. function randomInt(min, max) {
  12. return Math.floor(Math.random() * (max - min + 1)) + min;
  13. }
  14. /**
  15. * Get random element from array or string.
  16. * @param {Array|string} arr source
  17. * @returns array element or string character
  18. */
  19. function randomElement(arr) {
  20. return arr[randomInt(0, arr.length -1)];
  21. }
  22. /**
  23. * Generate random alphanumeric string.
  24. * @param {number} length expected string length
  25. * @returns {string} random string of specified length
  26. */
  27. function randomAlphanumStr(length) {
  28. var result = '';
  29. for (var i = 0; i < length; i += 1) {
  30. result += randomElement(ALPHANUM);
  31. }
  32. return result;
  33. }
  34. /**
  35. * Generates random hex number within the range [min, max]
  36. * @param min the minimum value for the generated number
  37. * @param max the maximum value for the generated number
  38. * @returns random hex number
  39. */
  40. function rangeRandomHex(min, max)
  41. {
  42. return randomInt(min, max).toString(16);
  43. }
  44. /**
  45. * Exported interface.
  46. */
  47. var RandomUtil = {
  48. /**
  49. * Generates hex number with length 4
  50. */
  51. random4digitsHex: function () {
  52. return rangeRandomHex(0x1000, 0xFFFF);
  53. },
  54. /**
  55. * Generates hex number with length 8
  56. */
  57. random8digitsHex: function () {
  58. return rangeRandomHex(0x10000000, 0xFFFFFFFF);
  59. },
  60. /**
  61. * Generates hex number with length 12
  62. */
  63. random12digitsHex: function () {
  64. return rangeRandomHex(0x100000000000, 0xFFFFFFFFFFFF);
  65. }
  66. };
  67. module.exports = RandomUtil;