Study this material in conjunction with : 6 Forms of Functions in JavaScript
Below is an example of a TypeScript program to demonstrate string handling by randomly generating five 5-letter words from the alphabet string. This program uses classes and objects for structure.
class RandomWordGenerator {
alphabet: string = "abcdefghijklmnopqrstuvwxyz";
// Method to generate a random 5-letter word
generateWord(): string {
let word = "";
for (let i = 0; i < 5; i++) {
const randomIndex = Math.floor(Math.random() * this.alphabet.length);
word += this.alphabet[randomIndex];
}
return word;
}
}
class WordList {
words: string[] = [];
// Method to add a word to the words array
addWord(word: string): void {
this.words.push(word);
}
// Method to display the words
displayWords(): void {
console.log("Generated Words: ", this.words.join(", "));
}
}
// Create objects of the classes
const randomWordGenerator = new RandomWordGenerator();
const wordList = new WordList();
// Generate five 5-letter words and add them to the words array
for (let i = 0; i < 5; i++) {
const word = randomWordGenerator.generateWord();
wordList.addWord(word);
}
// Display the generated words
wordList.displayWords();
Explanation:
RandomWordGenerator class: alphabet: a string containing all the letters of the alphabet. generateWord(): a method that generates a random 5-letter word. It selects a random character from alphabet five times and concatenates them to form a word. words: an array to hold the generated words. addWord(word: string): a method that adds a word to the words array. displayWords(): a method that displays the words stored in the words array. Creating objects of the classes: randomWordGenerator: an object of RandomWordGenerator class. wordList: an object of WordList class. Generating and displaying words: A for loop runs 5 times to generate five 5-letter words. Each generated word is added to the words array of the wordList object using the addWord() method. The displayWords() method is called on the wordList object to display the generated words. To run this program, ensure you have TypeScript installed, then compile the TypeScript code to JavaScript using the tsc command and execute the JavaScript code using the node command. bashCopy code
tsc filename.ts
node filename.js