Created
June 13, 2017 05:44
-
-
Save amackintosh/81cddf4120e0fa52701e3d07c669f817 to your computer and use it in GitHub Desktop.
Random Word Generator from Dictionary File
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
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