Skip to content

Instantly share code, notes, and snippets.

@ungarson
Last active July 13, 2019 08:53
Show Gist options
  • Save ungarson/4a1b78bd6a6c078c76b9ea0288780f90 to your computer and use it in GitHub Desktop.
Save ungarson/4a1b78bd6a6c078c76b9ea0288780f90 to your computer and use it in GitHub Desktop.
Random name generator in javascript using iterators
export default class RandomNameGenerator {
constructor(amountOfNames, lengthOfNames) {
this.amountOfNames = amountOfNames;
this.lengthOfNames = lengthOfNames;
this.names = new Array();
};
makeName(stringLength) {
let result = '';
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const charactersLength = characters.length;
for (let i = 0; i < stringLength; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
*[Symbol.iterator]() {
while(this.names.length < this.amountOfNames) {
let newName;
do {
newName = this.makeName(this.lengthOfNames);
this.names.push(newName);
} while (this.names.indexOf(newName) === -1);
yield newName;
}
}
}
// Example of usage
// console.log([...new RandomNameGenerator(5, 15)]); // 5 random names with length of 15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment