Skip to content

Commit 68ca0ce

Browse files
authored
merge: optimize the countVowels algo (#886)
* pref: optimize the count vowels algo simplify the algo by using regex and String.prototype.match method, and modified the JS Doc * fix: resolve all requests * pref: optimize the algo by regex ignore the useless traverse in best case by the help of regex and String.prototype.replace method * test: add four new test cases * Revert "test: add four new test cases" This reverts commit 4609833. * style: fromat with standard js
1 parent 9911410 commit 68ca0ce

File tree

1 file changed

+7
-11
lines changed

1 file changed

+7
-11
lines changed

String/CountVowels.js

+7-11
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
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 vowels
66
* @example countVowels("ABCDE") => 2
77
* @example countVowels("Hello") => 2
88
*/
@@ -11,15 +11,11 @@ const countVowels = (str) => {
1111
if (typeof str !== 'string') {
1212
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

2521
export { countVowels }

0 commit comments

Comments
 (0)