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.6KB

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