Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
;(function (namespace) {
'use strict'
namespace.randomlettergenerator = function (namespace) {
var total = 0
var lettersArray = []
/*
* Populates "lettersArray" and computes "total".
*/
;(function () {
var letters = {}
namespace.dictionaries.forEach(function (word) {
var i, len, letter
for (i = 0, len = word.length; i < len; i++) {
letter = word[i]
if (typeof letters[letter] === 'undefined') {
letters[letter] = { letter: letter, count: 1 }
lettersArray.push(letters[letter])
} else {
letters[letter].count += 1
}
total += 1
}
})
}())
/*
* Sorts by descending letter frequency
*/
lettersArray.sort(function (a, b) {
if (a.count > b.count) {
return -1
}
if (a.count < b.count) {
return 1
}
return 0
})
/**
* Random letter generator.
*/
function RandomLetterGenerator () {
this.lastIx = -1
}
/**
* Returns a random letter.
*
* @return Random letter.
*/
RandomLetterGenerator.prototype.next = function () {
var i = this.lastIx + 1
var len = lettersArray.length
var count = Math.random() * total
while (count > 0) {
if (i >= len) {
i = 0
}
count -= lettersArray[i].count
i++
}
this.lastIx = i
return lettersArray[i].letter
}
namespace.RandomLetterGenerator = RandomLetterGenerator
}
}((function () {
if (typeof window === 'undefined') {
return module.exports
} else {
return window
}
}())))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment