parent
40f1f2588e
commit
f161cc33b4
2 changed files with 62 additions and 21 deletions
@ -1,24 +1,32 @@ |
||||
var fs = require('fs'); |
||||
const fs = require('fs'); |
||||
|
||||
var DictionaryGenerator = function(options) { |
||||
//Options
|
||||
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'); |
||||
|
||||
//Load dictionary
|
||||
// Load dictionary
|
||||
fs.readFile(options.path, 'utf8', (err, data) => { |
||||
if (err) throw err; |
||||
|
||||
this.dictionary = data.split(/[\n\r]+/); |
||||
|
||||
if (readyCallback) readyCallback(); |
||||
}); |
||||
}; |
||||
} |
||||
|
||||
//Generates a dictionary-based key, of keyLength words
|
||||
DictionaryGenerator.prototype.createKey = function(keyLength) { |
||||
var text = ''; |
||||
for(var i = 0; i < keyLength; i++) |
||||
text += this.dictionary[Math.floor(Math.random() * this.dictionary.length)]; |
||||
// 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; |
||||
}; |
||||
} |
||||
|
||||
module.exports = DictionaryGenerator; |
||||
}; |
||||
|
@ -0,0 +1,33 @@ |
||||
/* global describe, it */ |
||||
|
||||
const assert = require('assert'); |
||||
|
||||
const fs = require('fs'); |
||||
|
||||
const Generator = require('../../lib/key_generators/dictionary'); |
||||
|
||||
describe('RandomKeyGenerator', function() { |
||||
describe('randomKey', function() { |
||||
it('should throw an error if given no options', () => { |
||||
assert.throws(() => { |
||||
new Generator(); |
||||
}, Error); |
||||
}); |
||||
|
||||
it('should throw an error if given no path', () => { |
||||
assert.throws(() => { |
||||
new Generator({}); |
||||
}, Error); |
||||
}); |
||||
|
||||
it('should return a key of the proper number of words from the given dictionary', () => { |
||||
const path = '/tmp/haste-server-test-dictionary'; |
||||
const words = ['cat']; |
||||
fs.writeFileSync(path, words.join('\n')); |
||||
|
||||
const gen = new Generator({path}, () => { |
||||
assert.equal('catcatcat', gen.createKey(3)); |
||||
}); |
||||
}); |
||||
}); |
||||
}); |
Loading…
Reference in new issue