find the kth longest word in a string in typescript

One approach to find the kth longest word in a string in TypeScript may involve splitting the string into an array of words, sorting the array in ascending order of word length, and returning the word at the kth index (accounting for 0-based indexing). Here’s an example implementation:

index.ts
function findKthLongestWord(str: string, k: number): string | undefined {
  // Split string into array of words
  const words: string[] = str.split(/\s+/);
  // Sort the array in ascending order of word length
  words.sort((a: string, b: string) => a.length - b.length);
  // Check if k is within bounds
  if (k >= words.length) {
    return undefined;
  }
  // Return the word at the kth index
  return words[k];
}
416 chars
13 lines

This function takes in two parameters: the string str and the index k. It first splits the string into an array of words, assuming that words are separated by one or more whitespace characters. It then sorts the array in ascending order of word length using the built-in sort() method and a comparator function that takes two words a and b and returns a negative, zero, or positive number depending on whether a is shorter than, equal to, or longer than b, respectively. Finally, it checks if k is within bounds, i.e., less than the length of the array, and returns the word at the kth index, or undefined if k is out of bounds.

Here's an example usage of the function:

index.ts
const str: string = "The quick brown fox jumps over the lazy dog";
const k: number = 2;
const kthLongestWord: string | undefined = findKthLongestWord(str, k);
console.log(`The ${k}th longest word in "${str}" is "${kthLongestWord}".`); // Output: The 2th longest word in "The quick brown fox jumps over the lazy dog" is "over".
327 chars
5 lines

This code snippet defines a string str and an index k, and calls the findKthLongestWord() function on str and k. It then logs a message to the console with the result, which should be the kth longest word in the string.

gistlibby LogSnag