index.js 2.0 KB

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