random.js 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738
  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 () { return random().toString(36).slice(2); };
  6. var getString = function (/* length */) {
  7. var str = getChunk(), length = arguments[0];
  8. if (!isValue(length)) return str;
  9. while (str.length < length) str += getChunk();
  10. return str.slice(0, length);
  11. };
  12. module.exports = function (/* options */) {
  13. var options = Object(arguments[0]), length = options.length, isUnique = options.isUnique;
  14. if (isValue(length)) length = toNaturalNumber(length);
  15. var str = getString(length);
  16. if (isUnique) {
  17. var count = 0;
  18. while (generated[str]) {
  19. if (++count === uniqTryLimit) {
  20. throw new Error(
  21. "Cannot generate random string.\n" +
  22. "String.random is not designed to effectively generate many short and " +
  23. "unique random strings"
  24. );
  25. }
  26. str = getString(length);
  27. }
  28. generated[str] = true;
  29. }
  30. return str;
  31. };