您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

RandomUtil.js 1.5KB

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