Commit 3b6934e3 authored by John Crepezzi's avatar John Crepezzi
Browse files

Phonetic key generator to es6 and add some tests

parent f161cc33
Loading
Loading
Loading
Loading
+20 −26
Original line number Diff line number Diff line
// Draws inspiration from pwgen and http://tools.arantius.com/password
var PhoneticKeyGenerator = function() {
  // No options
};

// 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();
  }
  return text;
const randOf = (collection) => {
  return () => {
    return collection[Math.floor(Math.random() * collection.length)];
  };
};

PhoneticKeyGenerator.consonants = 'bcdfghjklmnpqrstvwxyz';
PhoneticKeyGenerator.vowels = 'aeiou';
// Helper methods to get an random vowel or consonant
const randVowel = randOf('aeiou');
const randConsonant = randOf('bcdfghjklmnpqrstvwxyz');

// Get an random vowel
PhoneticKeyGenerator.prototype.randVowel = function() {
  return PhoneticKeyGenerator.vowels[
    Math.floor(Math.random() * PhoneticKeyGenerator.vowels.length)
  ];
};
module.exports = class PhoneticKeyGenerator {

// Get an random consonant
PhoneticKeyGenerator.prototype.randConsonant = function() {
  return PhoneticKeyGenerator.consonants[
    Math.floor(Math.random() * PhoneticKeyGenerator.consonants.length)
  ];
};
  // Generate a phonetic key of alternating consonant & vowel
  createKey(keyLength) {
    let text = '';
    const start = Math.round(Math.random());

module.exports = PhoneticKeyGenerator;
    for (let i = 0; i < keyLength; i++) {
      text += (i % 2 == start) ? randConsonant() : randVowel();
    }

    return text;
  }

};
+27 −0
Original line number Diff line number Diff line
/* 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]));
    });
  });
});