June 27th 2023

Reverse Vowels of a String — Typescript

Problem Description permalink

Given a string s, reverse only all the vowels in the string and return it.

The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both lower and upper cases, more than once.

Solution permalink

function isVowel(char: string): boolean {
return ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'].includes(char)
}

function reverseVowels(s: string): string {
const charsForWord = s
.split('')

var reversedVowels = charsForWord
.filter(isVowel)

return charsForWord
.map((char, i) => {
if (isVowel(char)){
return reversedVowels.pop()
}
return char
})
.join("")

};

Discussion permalink

At first I thougth I needed to reverse the vowels but I then discovered I could treat it as a stack and have them already in the right order. I might ship this code to prod but I would need much more testing. I wonder if it would be clearer to have a function: replace(word: string, testFn: (s: string) => boolean, replacements) That might be needless abstraction but it also might break up the problem into the three main pieces- take a word, have a test for each character (aside: wish there was a character type for the standard lib in JS), and then have a set of replacements.