-
-
Notifications
You must be signed in to change notification settings - Fork 25
/
index.js
95 lines (78 loc) · 2.42 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/*!
* randomatic <https://github.com/jonschlinkert/randomatic>
*
* Copyright (c) 2014-2017, Jon Schlinkert.
* Released under the MIT License.
*/
'use strict';
var isNumber = require('is-number');
var typeOf = require('kind-of');
var mathRandom = require('math-random');
/**
* Expose `randomatic`
*/
module.exports = randomatic;
module.exports.isCrypto = !!mathRandom.cryptographic;
/**
* Available mask characters
*/
var type = {
lower: 'abcdefghijklmnopqrstuvwxyz',
upper: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
number: '0123456789',
special: '~!@#$%^&()_+-={}[];\',.'
};
type.all = type.lower + type.upper + type.number + type.special;
/**
* Generate random character sequences of a specified `length`,
* based on the given `pattern`.
*
* @param {String} `pattern` The pattern to use for generating the random string.
* @param {String} `length` The length of the string to generate.
* @param {String} `options`
* @return {String}
* @api public
*/
function randomatic(pattern, length, options) {
if (typeof pattern === 'undefined') {
throw new Error('randomatic expects a string or number.');
}
var custom = false;
if (arguments.length === 1) {
if (typeof pattern === 'string') {
length = pattern.length;
} else if (isNumber(pattern)) {
options = {};
length = pattern;
pattern = '*';
}
}
if (typeOf(length) === 'object' && length.hasOwnProperty('chars')) {
options = length;
pattern = options.chars;
length = pattern.length;
custom = true;
}
var opts = options || {};
var mask = '';
var res = '';
// Characters to be used
if (pattern.indexOf('?') !== -1) mask += opts.chars;
if (pattern.indexOf('a') !== -1) mask += type.lower;
if (pattern.indexOf('A') !== -1) mask += type.upper;
if (pattern.indexOf('0') !== -1) mask += type.number;
if (pattern.indexOf('!') !== -1) mask += type.special;
if (pattern.indexOf('*') !== -1) mask += type.all;
if (custom) mask += pattern;
// Characters to exclude
if (opts.exclude) {
var exclude = typeOf(opts.exclude) === 'string' ? opts.exclude : opts.exclude.join('');
exclude = exclude.replace(new RegExp('[\\]]+', 'g'), '');
mask = mask.replace(new RegExp('[' + exclude + ']+', 'g'), '');
if(opts.exclude.indexOf(']') !== -1) mask = mask.replace(new RegExp('[\\]]+', 'g'), '');
}
while (length--) {
res += mask.charAt(parseInt(mathRandom() * mask.length, 10));
}
return res;
};