randomWord function

String randomWord([
  1. int length = 0
])

Generates a random string of the specified length. If the length is not provided, a random length between 2 and 15 is used. The generated string consists of random consonants and vowels in a pronounceable order.

Implementation

String randomWord([int length = 0]) {
  length = length < 1 ? randomInt(2, 15) : length;
  String word = '';

  if (length == 1) {
    return lowerVowels.randomItem!;
  }

  while (word.length < length) {
    String consonant = lowerConsonants.randomItem!;
    if (consonant == 'q' && word.length + 3 <= length) {
      word += 'qu';
    } else {
      while (consonant == 'q') {
        consonant = lowerConsonants.randomItem!;
      }
      if (word.length + 1 <= length) {
        word += consonant;
      }
    }

    if (word.length + 1 <= length) {
      word += lowerVowels.randomItem!;
    }
  }

  return word;
}