-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
60 lines (52 loc) · 1.38 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
var secureRandom = require('secure-random');
var _ = require('lodash');
var dw = {};
dw.en = require('diceware-wordlist-en');
dw.swe = require('diceware-wordlist-swe');
dw.jp = require('diceware-wordlist-jp');
function getRandomInt(min, max) {
// Create byte array and fill with 1 random number
var byteArray = secureRandom(1, {type: 'Uint8Array'})
var range = max - min + 1;
var max_range = 256;
if (byteArray[0] >= Math.floor(max_range / range) * range)
return getRandomInt(min, max);
return min + (byteArray[0] % range);
}
function diceRoll() {
return getRandomInt(1, 6);
}
function diceSeq(count) {
var seq = [];
for(var i=0; i<count; i++) {
seq.push(diceRoll())
}
return seq.join("");
}
function getDices() {
return diceSeq(5);
}
function getRandomWord(language) {
return dw[language][getDices()];
}
function getRandomPassword(options) {
options = _.assign({
'language': 'en',
'wordcount': 6,
'format': 'string',
}, options);
if (!_.includes(['en', 'swe', 'jp'], options.language)) {
throw(new Error("Unsupported language: "+options.language));
}
var words = [];
for(var i=0; i<options.wordcount; i++) {
words.push(getRandomWord(options.language));
}
if (options.format === 'array') {
return words;
}
else {
return words.join(' ');
}
}
module.exports = getRandomPassword;