random.js 746 B

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