Skip to content

Commit a2822e1

Browse files
committed
pref: optimize the count vowels algo
simplify the algo by using regex and String.prototype.match method, and modified the JS Doc
1 parent 833d05d commit a2822e1

File tree

1 file changed

+9
-13
lines changed

1 file changed

+9
-13
lines changed

String/CountVowels.js

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,21 @@
11
/**
22
* @function countVowels
33
* @description Given a string of words or phrases, count the number of vowels.
4-
* @param {String} url - The input string
5-
* @return {Number} count
4+
* @param {String} str - The input string
5+
* @return {Number} - The number of vowel
66
* @example countVowels("ABCDE") => 2
77
* @example countVowels("Hello") => 2
88
*/
99

1010
const countVowels = (str) => {
1111
if (typeof str !== 'string') {
12-
throw new TypeError('Input should be a string')
12+
throw new TypeError('Input should be a string');
1313
}
14-
const vowels = new Set(['a', 'e', 'i', 'o', 'u'])
15-
let count = 0
16-
for (let i = 0; i < str.length; i++) {
17-
const char = str[i].toLowerCase()
18-
if (vowels.has(char)) {
19-
count++
20-
}
21-
}
22-
return count
14+
15+
const vowelRegex = /[aeiou]/gi;
16+
const vowelsArray = str.match(vowelRegex) || [];
17+
18+
return vowelsArray.length;
2319
}
2420

25-
export { countVowels }
21+
export { countVowels };

0 commit comments

Comments
 (0)