mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-06 09:28:26 +08:00
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 4609833da146beafe839682d7558edf9f64c96fc. * style: fromat with standard js
This commit is contained in:
@ -1,8 +1,8 @@
|
|||||||
/**
|
/**
|
||||||
* @function countVowels
|
* @function countVowels
|
||||||
* @description Given a string of words or phrases, count the number of vowels.
|
* @description Given a string of words or phrases, count the number of vowels.
|
||||||
* @param {String} url - The input string
|
* @param {String} str - The input string
|
||||||
* @return {Number} count
|
* @return {Number} - The number of vowels
|
||||||
* @example countVowels("ABCDE") => 2
|
* @example countVowels("ABCDE") => 2
|
||||||
* @example countVowels("Hello") => 2
|
* @example countVowels("Hello") => 2
|
||||||
*/
|
*/
|
||||||
@ -11,15 +11,11 @@ const countVowels = (str) => {
|
|||||||
if (typeof str !== 'string') {
|
if (typeof str !== 'string') {
|
||||||
throw new TypeError('Input should be a string')
|
throw new TypeError('Input should be a string')
|
||||||
}
|
}
|
||||||
const vowels = new Set(['a', 'e', 'i', 'o', 'u'])
|
|
||||||
let count = 0
|
const vowelRegex = /[aeiou]/gi
|
||||||
for (let i = 0; i < str.length; i++) {
|
const vowelsArray = str.match(vowelRegex) || []
|
||||||
const char = str[i].toLowerCase()
|
|
||||||
if (vowels.has(char)) {
|
return vowelsArray.length
|
||||||
count++
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return count
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export { countVowels }
|
export { countVowels }
|
||||||
|
Reference in New Issue
Block a user