Front end of the Slack clone application.

random.js 1.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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. };