2017-11-01 00:55:59 +00:00
|
|
|
const fs = require('fs');
|
2017-06-26 15:17:52 +00:00
|
|
|
|
2017-11-01 00:55:59 +00:00
|
|
|
module.exports = class DictionaryGenerator {
|
2017-06-26 16:03:18 +00:00
|
|
|
|
2017-11-01 00:55:59 +00: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 15:17:52 +00:00
|
|
|
|
2017-11-01 00:55:59 +00: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;
|
|
|
|
}
|
|
|
|
|
|
|
|
};
|