Last active
January 16, 2018 19:58
-
-
Save vontell/a96697e0de86ef6f1afed7b5d9edb733 to your computer and use it in GitHub Desktop.
001 Load Valid Words
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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