Skip to content

Instantly share code, notes, and snippets.

@vontell
Last active January 16, 2018 19:58
Show Gist options
  • Save vontell/a96697e0de86ef6f1afed7b5d9edb733 to your computer and use it in GitHub Desktop.
Save vontell/a96697e0de86ef6f1afed7b5d9edb733 to your computer and use it in GitHub Desktop.
001 Load Valid Words
// Predefined constants
const wordFilePath = "resources/google-10000-english-usa-no-swears.txt";
const minWordLength = 3;
const maxWordLength = 6;
// Cached global variables
var words = []
/**
* Loads a list of words from the file at `wordFilePath`, which should contain
* a list of newline-delimited words. Uses lineReader to do this in a buffered
* and asynchronous manner.
* callback - A function that gets called when the file is done being read
* (callback should not take any parameters)
*/
function loadValidWords(callback) {
// If we already loaded the words, just return the already-loaded words!
if (words.length > 0) {
return words;
}
// Otherwise, startup the buffered reader
var instance = lineReader.createInterface({
input: fs.createReadStream(wordFilePath)
});
// If a line is encountered, add it to our list if it satisfies the length
// constraints
instance.on('line', function (line) {
var wordLength = line.length;
if (wordLength >= minWordLength && wordLength <= maxWordLength)
words.push(line);
});
// Once finished, call the callback
instance.on('close', function (line) {
callback();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment