Last active
July 13, 2019 08:53
-
-
Save ungarson/4a1b78bd6a6c078c76b9ea0288780f90 to your computer and use it in GitHub Desktop.
Random name generator in javascript using iterators
This file contains hidden or 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
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