Skip to content

Instantly share code, notes, and snippets.

@robotlolita
Forked from zlepper/key-gen.js
Last active Apr 11, 2016
Embed
What would you like to do?
var fs = require("fs");
var helpers = require("./helpers");
var path = require("path");
function readFile(path, options) {
return new Promise(function(resolve, reject) {
fs.readFile(path, options, function(err, data) {
if (err) reject(err);
else resolve(data);
})
})
}
function loadData() {
"use strict";
var adjectivesPath = path.join(__dirname, "txt", "adjectives.txt");
var nounPath = path.join(__dirname, "txt", "nouns.txt");
return Promise.all([
readFile(adjectivesPath).then(data => data.split(/\n|\r\n/).map(x => helpers.capitalizeFirstLetter(x).trim())),
readFile(nounPath).then(data => data.split(/\n|\r\n/).map(x => helpers.capitalizeFirstLetter(x).trim())),
]);
}
var data = loadData(); // data is now a promise containing both arrays
function generateKey() {
"use strict";
return data.then(([adjectives, nouns]) => {
var adjIndex = Math.floor(Math.random() * adjectives.length);
var secondAdjIndex = Math.floor(Math.random() * adjectives.length);
while (adjIndex === secondAdjIndex) {
secondAdjIndex = Math.floor(Math.random() * adjectives.length);
}
var nounIndex = Math.floor(Math.random() * adjectives.length);
return adjectives[adjIndex] + adjectives[secondAdjIndex] + nouns[nounIndex];
})
}
// Now you use it as:
generateKey().then(thisIsYourKey => { doSomethingWithIt() })
module.exports = generateKey;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment