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

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