2 * randomatic <https://github.com/jonschlinkert/randomatic>
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)
11 var isNumber = require('is-number');
12 var typeOf = require('kind-of');
18 module.exports = randomatic;
21 * Available mask characters
25 lower: 'abcdefghijklmnopqrstuvwxyz',
26 upper: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
28 special: '~!@#$%^&()_+-={}[];\',.'
31 type.all = type.lower + type.upper + type.number;
34 * Generate random character sequences of a specified `length`,
35 * based on the given `pattern`.
37 * @param {String} `pattern` The pattern to use for generating the random string.
38 * @param {String} `length` The length of the string to generate.
39 * @param {String} `options`
44 function randomatic(pattern, length, options) {
45 if (typeof pattern === 'undefined') {
46 throw new Error('randomatic expects a string or number.');
50 if (arguments.length === 1) {
51 if (typeof pattern === 'string') {
52 length = pattern.length;
54 } else if (isNumber(pattern)) {
55 options = {}; length = pattern; pattern = '*';
59 if (typeOf(length) === 'object' && length.hasOwnProperty('chars')) {
61 pattern = options.chars;
62 length = pattern.length;
66 var opts = options || {};
70 // Characters to be used
71 if (pattern.indexOf('?') !== -1) mask += opts.chars;
72 if (pattern.indexOf('a') !== -1) mask += type.lower;
73 if (pattern.indexOf('A') !== -1) mask += type.upper;
74 if (pattern.indexOf('0') !== -1) mask += type.number;
75 if (pattern.indexOf('!') !== -1) mask += type.special;
76 if (pattern.indexOf('*') !== -1) mask += type.all;
77 if (custom) mask += pattern;
80 res += mask.charAt(parseInt(Math.random() * mask.length, 10));