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 2.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /**
  2. * Alphanumeric characters.
  3. * @const
  4. */
  5. const ALPHANUM
  6. = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  7. /**
  8. * Hexadecimal digit characters.
  9. * @const
  10. */
  11. const HEX_DIGITS = '0123456789abcdef';
  12. /**
  13. * Generate a string with random alphanumeric characters with a specific length.
  14. *
  15. * @param {number} length - The length of the string to return.
  16. * @returns {string} A string of random alphanumeric characters with the
  17. * specified length.
  18. */
  19. export function randomAlphanumString(length) {
  20. return _randomString(length, ALPHANUM);
  21. }
  22. /**
  23. * Get random element of array or string.
  24. *
  25. * @param {Array|string} arr - Source.
  26. * @returns {Array|string} Array element or string character.
  27. */
  28. export function randomElement(arr) {
  29. return arr[randomInt(0, arr.length - 1)];
  30. }
  31. /**
  32. * Returns a random hex digit.
  33. *
  34. * @returns {Array|string}
  35. */
  36. export function randomHexDigit() {
  37. return randomElement(HEX_DIGITS);
  38. }
  39. /**
  40. * Generates a string of random hexadecimal digits with a specific length.
  41. *
  42. * @param {number} length - The length of the string to return.
  43. * @returns {string} A string of random hexadecimal digits with the specified
  44. * length.
  45. */
  46. export function randomHexString(length) {
  47. return _randomString(length, HEX_DIGITS);
  48. }
  49. /**
  50. * Generates random int within the range [min, max].
  51. *
  52. * @param {number} min - The minimum value for the generated number.
  53. * @param {number} max - The maximum value for the generated number.
  54. * @returns {number} Random int number.
  55. */
  56. export function randomInt(min, max) {
  57. return Math.floor(Math.random() * (max - min + 1)) + min;
  58. }
  59. /**
  60. * Generates a string of random characters with a specific length.
  61. *
  62. * @param {number} length - The length of the string to return.
  63. * @param {string} characters - The characters from which the returned string is
  64. * to be constructed.
  65. * @private
  66. * @returns {string} A string of random characters with the specified length.
  67. */
  68. function _randomString(length, characters) {
  69. let result = '';
  70. for (let i = 0; i < length; ++i) {
  71. result += randomElement(characters);
  72. }
  73. return result;
  74. }