index.js 2.0 KB

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