Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

RandomUtil.js 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. * @returns {string} A string of random characters with the specified length.
  66. */
  67. function _randomString(length, characters) {
  68. let result = '';
  69. for (let i = 0; i < length; ++i) {
  70. result += randomElement(characters);
  71. }
  72. return result;
  73. }