index.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*!
  2. * randomatic <https://github.com/jonschlinkert/randomatic>
  3. *
  4. * Copyright (c) 2014-2017, Jon Schlinkert.
  5. * Released under the MIT License.
  6. */
  7. 'use strict';
  8. var isNumber = require('is-number');
  9. var typeOf = require('kind-of');
  10. var mathRandom = require('math-random');
  11. /**
  12. * Expose `randomatic`
  13. */
  14. module.exports = randomatic;
  15. module.exports.isCrypto = !!mathRandom.cryptographic;
  16. /**
  17. * Available mask characters
  18. */
  19. var type = {
  20. lower: 'abcdefghijklmnopqrstuvwxyz',
  21. upper: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
  22. number: '0123456789',
  23. special: '~!@#$%^&()_+-={}[];\',.'
  24. };
  25. type.all = type.lower + type.upper + type.number + type.special;
  26. /**
  27. * Generate random character sequences of a specified `length`,
  28. * based on the given `pattern`.
  29. *
  30. * @param {String} `pattern` The pattern to use for generating the random string.
  31. * @param {String} `length` The length of the string to generate.
  32. * @param {String} `options`
  33. * @return {String}
  34. * @api public
  35. */
  36. function randomatic(pattern, length, options) {
  37. if (typeof pattern === 'undefined') {
  38. throw new Error('randomatic expects a string or number.');
  39. }
  40. var custom = false;
  41. if (arguments.length === 1) {
  42. if (typeof pattern === 'string') {
  43. length = pattern.length;
  44. } else if (isNumber(pattern)) {
  45. options = {};
  46. length = pattern;
  47. pattern = '*';
  48. }
  49. }
  50. if (typeOf(length) === 'object' && length.hasOwnProperty('chars')) {
  51. options = length;
  52. pattern = options.chars;
  53. length = pattern.length;
  54. custom = true;
  55. }
  56. var opts = options || {};
  57. var mask = '';
  58. var res = '';
  59. // Characters to be used
  60. if (pattern.indexOf('?') !== -1) mask += opts.chars;
  61. if (pattern.indexOf('a') !== -1) mask += type.lower;
  62. if (pattern.indexOf('A') !== -1) mask += type.upper;
  63. if (pattern.indexOf('0') !== -1) mask += type.number;
  64. if (pattern.indexOf('!') !== -1) mask += type.special;
  65. if (pattern.indexOf('*') !== -1) mask += type.all;
  66. if (custom) mask += pattern;
  67. while (length--) {
  68. res += mask.charAt(parseInt(mathRandom() * mask.length, 10));
  69. }
  70. return res;
  71. };