diff --git a/lib/key_generators/phonetic.js b/lib/key_generators/phonetic.js index cb13a19..f281f6b 100644 --- a/lib/key_generators/phonetic.js +++ b/lib/key_generators/phonetic.js @@ -1,33 +1,27 @@ // Draws inspiration from pwgen and http://tools.arantius.com/password -var PhoneticKeyGenerator = function() { - // No options + +const randOf = (collection) => { + return () => { + return collection[Math.floor(Math.random() * collection.length)]; + }; }; -// Generate a phonetic key -PhoneticKeyGenerator.prototype.createKey = function(keyLength) { - var text = ''; - var start = Math.round(Math.random()); - for (var i = 0; i < keyLength; i++) { - text += (i % 2 == start) ? this.randConsonant() : this.randVowel(); +// Helper methods to get an random vowel or consonant +const randVowel = randOf('aeiou'); +const randConsonant = randOf('bcdfghjklmnpqrstvwxyz'); + +module.exports = class PhoneticKeyGenerator { + + // Generate a phonetic key of alternating consonant & vowel + createKey(keyLength) { + let text = ''; + const start = Math.round(Math.random()); + + for (let i = 0; i < keyLength; i++) { + text += (i % 2 == start) ? randConsonant() : randVowel(); + } + + return text; } - return text; + }; - -PhoneticKeyGenerator.consonants = 'bcdfghjklmnpqrstvwxyz'; -PhoneticKeyGenerator.vowels = 'aeiou'; - -// Get an random vowel -PhoneticKeyGenerator.prototype.randVowel = function() { - return PhoneticKeyGenerator.vowels[ - Math.floor(Math.random() * PhoneticKeyGenerator.vowels.length) - ]; -}; - -// Get an random consonant -PhoneticKeyGenerator.prototype.randConsonant = function() { - return PhoneticKeyGenerator.consonants[ - Math.floor(Math.random() * PhoneticKeyGenerator.consonants.length) - ]; -}; - -module.exports = PhoneticKeyGenerator; diff --git a/test/key_generators/phonetic_spec.js b/test/key_generators/phonetic_spec.js new file mode 100644 index 0000000..14ad9e8 --- /dev/null +++ b/test/key_generators/phonetic_spec.js @@ -0,0 +1,27 @@ +/* global describe, it */ + +const assert = require('assert'); + +const Generator = require('../../lib/key_generators/phonetic'); + +const vowels = 'aeiou'; +const consonants = 'bcdfghjklmnpqrstvwxyz'; + +describe('RandomKeyGenerator', () => { + describe('randomKey', () => { + it('should return a key of the proper length', () => { + const gen = new Generator(); + assert.equal(6, gen.createKey(6).length); + }); + + it('should alternate consonants and vowels', () => { + const gen = new Generator(); + + const key = gen.createKey(3); + + assert.ok(consonants.includes(key[0])); + assert.ok(consonants.includes(key[2])); + assert.ok(vowels.includes(key[1])); + }); + }); +});