index.js 2.0 KB

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