Problems › TypeScript › warmup
Reverse the order of the words
A text filter turns a sentence back to front, word by word, without disturbing the words themselves.
- Only the order of the words changes; the letters inside each word stay put.
- Runs of whitespace collapse to one space, and the ends are trimmed.
- Text with no words gives an empty string.
reverseWords(text: string) → string
Where you start
function reverseWords(text: string): string {
}
Worked examples
| Call | Result |
|---|---|
reverseWords("the quick brown fox") | "fox brown quick the" |
reverseWords(" a b ") | "b a" |
reverseWords("one") | "one" |
reverseWords("") | "" |
Hint
Split on whitespace, reverse the list, join with a single space.
Reference solution in TypeScript
function reverseWords(text: string): string {
return text.split(/\s+/).filter((w) => w.length > 0).reverse().join(' ');
}