2017-11-01 08:55:59 +08:00
|
|
|
const fs = require('fs');
|
2017-06-26 23:17:52 +08:00
|
|
|
|
2017-11-01 08:55:59 +08:00
|
|
|
module.exports = class DictionaryGenerator {
|
2017-06-27 00:03:18 +08:00
|
|
|
|
2017-11-01 08:55:59 +08:00
|
|
|
constructor(options, readyCallback) {
|
|
|
|
// Check options format
|
|
|
|
if (!options) throw Error('No options passed to generator');
|
|
|
|
if (!options.path) throw Error('No dictionary path specified in options');
|
|
|
|
|
|
|
|
// Load dictionary
|
|
|
|
fs.readFile(options.path, 'utf8', (err, data) => {
|
|
|
|
if (err) throw err;
|
|
|
|
|
|
|
|
this.dictionary = data.split(/[\n\r]+/);
|
|
|
|
|
|
|
|
if (readyCallback) readyCallback();
|
|
|
|
});
|
|
|
|
}
|
2017-06-26 23:17:52 +08:00
|
|
|
|
2017-11-01 08:55:59 +08:00
|
|
|
// Generates a dictionary-based key, of keyLength words
|
|
|
|
createKey(keyLength) {
|
|
|
|
let text = '';
|
|
|
|
|
|
|
|
for (let i = 0; i < keyLength; i++) {
|
|
|
|
const index = Math.floor(Math.random() * this.dictionary.length);
|
|
|
|
text += this.dictionary[index];
|
|
|
|
}
|
|
|
|
|
|
|
|
return text;
|
|
|
|
}
|
|
|
|
|
|
|
|
};
|