random.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. "use strict";
  2. var isObject = require("type/object/is")
  3. , ensureNaturalNumber = require("type/natural-number/ensure")
  4. , ensureString = require("type/string/ensure");
  5. var generated = Object.create(null), random = Math.random, uniqTryLimit = 100;
  6. var getChunk = function () { return random().toString(36).slice(2); };
  7. var getString = function (length, charset) {
  8. var str;
  9. if (charset) {
  10. var charsetLength = charset.length;
  11. str = "";
  12. for (var i = 0; i < length; ++i) {
  13. str += charset.charAt(Math.floor(Math.random() * charsetLength));
  14. }
  15. return str;
  16. }
  17. str = getChunk();
  18. if (length === null) return str;
  19. while (str.length < length) str += getChunk();
  20. return str.slice(0, length);
  21. };
  22. module.exports = function (/* options */) {
  23. var options = arguments[0];
  24. if (!isObject(options)) options = {};
  25. var length = ensureNaturalNumber(options.length, { "default": 10 })
  26. , isUnique = options.isUnique
  27. , charset = ensureString(options.charset, { isOptional: true });
  28. var str = getString(length, charset);
  29. if (isUnique) {
  30. var count = 0;
  31. while (generated[str]) {
  32. if (++count === uniqTryLimit) {
  33. throw new Error(
  34. "Cannot generate random string.\n" +
  35. "String.random is not designed to effectively generate many short and " +
  36. "unique random strings"
  37. );
  38. }
  39. str = getString(length);
  40. }
  41. generated[str] = true;
  42. }
  43. return str;
  44. };