-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.js
50 lines (41 loc) · 1.16 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
/**
* @copyright Maichong Software Ltd. 2016 http://maichong.it
* @date 2016-01-20
* @author Liang <[email protected]>
*/
'use strict';
var numbers = '0123456789';
var letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
var specials = '~!@#$%^*()_+-=[]{}|;:,./<>?';
/**
* Generate random string
* @param {Number} length
* @param {Object} options
*/
function random(length, options) {
length || (length = 8);
options || (options = {});
var chars = '';
var result = '';
if (options === true) {
chars = numbers + letters + specials;
} else if (typeof options == 'string') {
chars = options;
} else {
if (options.numbers !== false) {
chars += (typeof options.numbers == 'string') ? options.numbers : numbers;
}
if (options.letters !== false) {
chars += (typeof options.letters == 'string') ? options.letters : letters;
}
if (options.specials) {
chars += (typeof options.specials == 'string') ? options.specials : specials;
}
}
while (length > 0) {
length--;
result += chars[Math.floor(Math.random() * chars.length)];
}
return result;
}
module.exports = random.default = random;