random.js 721 B

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