2 * randomatic <https://github.com/jonschlinkert/randomatic>
4 * Copyright (c) 2014-2017, Jon Schlinkert.
5 * Released under the MIT License.
10 var isNumber = require('is-number');
11 var typeOf = require('kind-of');
12 var mathRandom = require('math-random');
18 module.exports = randomatic;
19 module.exports.isCrypto = !!mathRandom.cryptographic;
22 * Available mask characters
26 lower: 'abcdefghijklmnopqrstuvwxyz',
27 upper: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
29 special: '~!@#$%^&()_+-={}[];\',.'
32 type.all = type.lower + type.upper + type.number + type.special;
35 * Generate random character sequences of a specified `length`,
36 * based on the given `pattern`.
38 * @param {String} `pattern` The pattern to use for generating the random string.
39 * @param {String} `length` The length of the string to generate.
40 * @param {String} `options`
45 function randomatic(pattern, length, options) {
46 if (typeof pattern === 'undefined') {
47 throw new Error('randomatic expects a string or number.');
51 if (arguments.length === 1) {
52 if (typeof pattern === 'string') {
53 length = pattern.length;
55 } else if (isNumber(pattern)) {
62 if (typeOf(length) === 'object' && length.hasOwnProperty('chars')) {
64 pattern = options.chars;
65 length = pattern.length;
69 var opts = options || {};
73 // Characters to be used
74 if (pattern.indexOf('?') !== -1) mask += opts.chars;
75 if (pattern.indexOf('a') !== -1) mask += type.lower;
76 if (pattern.indexOf('A') !== -1) mask += type.upper;
77 if (pattern.indexOf('0') !== -1) mask += type.number;
78 if (pattern.indexOf('!') !== -1) mask += type.special;
79 if (pattern.indexOf('*') !== -1) mask += type.all;
80 if (custom) mask += pattern;
82 // Characters to exclude
84 var exclude = typeOf(opts.exclude) === 'string' ? opts.exclude : opts.exclude.join('');
85 exclude = exclude.replace(new RegExp('[\\]]+', 'g'), '');
86 mask = mask.replace(new RegExp('[' + exclude + ']+', 'g'), '');
88 if(opts.exclude.indexOf(']') !== -1) mask = mask.replace(new RegExp('[\\]]+', 'g'), '');
92 res += mask.charAt(parseInt(mathRandom() * mask.length, 10));