Rewrote (and fixed) dictionary key generator

This commit is contained in:
zneix 2020-08-29 00:40:36 +02:00
parent 2e2b69c43c
commit 1efc62a8c5
1 changed files with 15 additions and 19 deletions

View File

@ -1,32 +1,28 @@
const winston = require('winston');
const fs = require('fs');
module.exports = class DictionaryGenerator {
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');
constructor({ path } = {}, readyCallback){
//check for dictionary path
if (!path){
winston.error('No dictionary path specified in options');
process.exit(1);
}
// Load dictionary
fs.readFile(options.path, 'utf8', (err, data) => {
if (err) throw err;
//load dictionary
if (!fs.existsSync(path)){
winston.error(`Dictionary file "${path}" doesn't exist`);
process.exit(1);
}
this.dictionary = data.split(/[\n\r]+/);
if (readyCallback) readyCallback();
});
this.dictionary = fs.readFileSync(path).toString().split(/\s+/gm);
if (readyCallback) readyCallback();
}
// 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;
return Array(keyLength).fill().map(() => this.dictionary[ Math.floor(Math.random() * this.dictionary.length) ] ).join('');
}
};