Wednesday, 23 September 2020

TypeScript - generate random word

This method will generate random string of n-letter length with lowercase letters:
  /**
   * Generate random lowercase word
   * @param {number} length Word length
   * @returns Random n-letter word
   */
  randomWord(length: number): string {
    let result = '';
    for (let index = 0; index < length; index++) {
      // one of 26 en letters, 'a' = 97
      const ascii = Math.floor(Math.random() * 26 + 97);
      result += String.fromCharCode(ascii);
    }
    return result;
  }

No comments:

Post a Comment