How to find the largest and the smallest word in a string with TypeScript

2 Answers

0 votes
const s : string = "typescript php python c++ c c# java"
  
let max : string = "";
let min : string = s;
   
const words : string[] = s.split(" "); 
   
for (var i = 0; i < words.length; i++) {
    if (words[i].length > max.length)
        max = words[i];    
    if (words[i].length < min.length)
        min = words[i];
}
  
console.log("Largest word: " + max);
console.log("Smallest word: " + min);
     
     
          
  
/*
  
run:
  
"Largest word: typescript" 
"Smallest word: c" 
  
*/

 



answered Nov 12, 2022 by avibootz
0 votes
/**
 * Finds the largest and smallest words in a given string.
 * 
 * @param text - The input string containing words.
 * @returns A tuple containing [largestWord, smallestWord].
 */
function findLargestAndSmallestWords(text: string): [string, string] {
    if (!text || text.trim() === '') {
        return ['', ''];
    }

    // Split the string into words using a regular expression for arbitrary whitespace
    const words: string[] = text.trim().split(/\s+/);
    
    if (words.length === 0) {
        return ['', ''];
    }

    let largest: string = words[0];
    let smallest: string = words[0];

    // Iterate through the words to find extrema based on length
    for (const word of words) {
        if (word.length > largest.length) {
            largest = word;
        }
        if (word.length < smallest.length) {
            smallest = word;
        }
    }

    return [largest, smallest];
}

/**
 * Main execution function.
 */
function main(): void {
    const s: string = "TypeScript is a strongly typed programming language that builds on JavaScript";

    // Destructure the returned tuple with explicit type safety
    const [largest, smallest]: [string, string] = findLargestAndSmallestWords(s);

    console.log(`Largest word:  ${largest}`);
    console.log(`Smallest word: ${smallest}`);
}

// Execute the main function
main();


/*
run:

Largest word:  programming
Smallest word: a

*/

 



answered Nov 5 by avibootz
...