random.js 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. "use strict";
  2. var isValue = require("../object/is-value")
  3. , toNaturalNumber = require("../number/to-pos-integer");
  4. var generated = Object.create(null), random = Math.random, uniqTryLimit = 100;
  5. var getChunk = function () {
  6. return random()
  7. .toString(36)
  8. .slice(2);
  9. };
  10. var getString = function (/* length */) {
  11. var str = getChunk(), length = arguments[0];
  12. if (!isValue(length)) return str;
  13. while (str.length < length) str += getChunk();
  14. return str.slice(0, length);
  15. };
  16. module.exports = function (/* options */) {
  17. var options = Object(arguments[0]), length = options.length, isUnique = options.isUnique;
  18. if (isValue(length)) length = toNaturalNumber(length);
  19. var str = getString(length);
  20. if (isUnique) {
  21. var count = 0;
  22. while (generated[str]) {
  23. if (++count === uniqTryLimit) {
  24. throw new Error(
  25. "Cannot generate random string.\n" +
  26. "String.random is not designed to effectively generate many short and " +
  27. "unique random strings"
  28. );
  29. }
  30. str = getString(length);
  31. }
  32. generated[str] = true;
  33. }
  34. return str;
  35. };