Random username

by Abhishek Kumar

JavaScript

class UsernameGenerator {
  constructor(words) {
    this.words = words || [
      "apple",
      "banana",
      "cherry",
      "date",
      "elderberry",
      "fig",
      "grape",
      "honeydew",
      "kiwi",
      "lemon",
      "mango",
      "nectarine",
      "orange",
      "papaya",
      "quince",
      "raspberry",
      "strawberry",
      "tangerine",
      "ugli",
      "vanilla",
      "watermelon",
      "xigua",
      "yam",
      "zucchini",
    ]
  }

  getRandomWord() {
    const randomIndex = Math.floor(Math.random() * this.words.length)
    return this.words[randomIndex]
  }

  generateRandomUsername(minLength = 8) {
    let username = ""

    while (username.length < minLength) {
      username += this.getRandomWord()
    }

    // Trim to ensure it is at least minLength
    return username.substring(0, minLength)
  }
}

// Example usage
const usernameGenerator = new UsernameGenerator()
const randomUsername = usernameGenerator.generateRandomUsername()
console.log(randomUsername)