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.

29 lines
746 B

4 years ago
  1. 'use strict';
  2. /* global crypto:true */
  3. var crypto = require('crypto');
  4. // This string has length 32, a power of 2, so the modulus doesn't introduce a
  5. // bias.
  6. var _randomStringChars = 'abcdefghijklmnopqrstuvwxyz012345';
  7. module.exports = {
  8. string: function(length) {
  9. var max = _randomStringChars.length;
  10. var bytes = crypto.randomBytes(length);
  11. var ret = [];
  12. for (var i = 0; i < length; i++) {
  13. ret.push(_randomStringChars.substr(bytes[i] % max, 1));
  14. }
  15. return ret.join('');
  16. }
  17. , number: function(max) {
  18. return Math.floor(Math.random() * max);
  19. }
  20. , numberString: function(max) {
  21. var t = ('' + (max - 1)).length;
  22. var p = new Array(t + 1).join('0');
  23. return (p + this.number(max)).slice(-t);
  24. }
  25. };