Skip to content

Instantly share code, notes, and snippets.

@amackintosh
Created June 13, 2017 05:44
Show Gist options
  • Save amackintosh/81cddf4120e0fa52701e3d07c669f817 to your computer and use it in GitHub Desktop.
Save amackintosh/81cddf4120e0fa52701e3d07c669f817 to your computer and use it in GitHub Desktop.
Random Word Generator from Dictionary File
var fs = require('fs');
sampleFile = './words.txt';
function getRandomWord(relativeFilePath) {
try {
// Read file and get words
var text = fs.readFileSync(relativeFilePath, 'utf8');
var words = text.split(/\s/);
// Map words into an array
words = words.map(word => {
return word.trim();
});
// Filter garbage content out
words = words.filter(word => {
return word.length > 0;
});
// Pick random word, strip non-alphanumeric garbage and return picked word
return words[Math.floor(Math.random() * words.length)].replace(/\W/g, '');
} catch (e) {
throw 'ERROR: Shits on fire, yo!\n' + e.stack;
};
};
console.log(getRandomWord(sampleFile));
console.log(getRandomWord(sampleFile));
console.log(getRandomWord(sampleFile));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment