Solución
solution.tsTypeScript
export function topNWords(text: string, n: number): string[] {
const seen = new Map<string, number>()
// Fill map like ['foo', 3] => [word, times seen]
for (const word of text.toLowerCase().split(/\s+/)) {
seen.set(word, (seen.get(word) ?? 0) + 1)
}
return [...seen]
.sort(([wordA, countA], [wordB, countB]) =>
countB - countA || wordA.localeCompare(wordB)
) // Sort by times seen desc or alphabetically
.slice(0, n) // Cut the section you need
.map(([word]) => word); // Return keys only
}0respuestas