From a2822e17b6ec606efd6b2ef1bd21692502fcc503 Mon Sep 17 00:00:00 2001 From: Fahim Faisaal Date: Wed, 16 Feb 2022 19:47:01 +0600 Subject: [PATCH] pref: optimize the count vowels algo simplify the algo by using regex and String.prototype.match method, and modified the JS Doc --- String/CountVowels.js | 22 +++++++++------------- 1 file changed, 9 insertions(+), 13 deletions(-) diff --git a/String/CountVowels.js b/String/CountVowels.js index 9772c28f0..71939e388 100644 --- a/String/CountVowels.js +++ b/String/CountVowels.js @@ -1,25 +1,21 @@ /** * @function countVowels * @description Given a string of words or phrases, count the number of vowels. - * @param {String} url - The input string - * @return {Number} count + * @param {String} str - The input string + * @return {Number} - The number of vowel * @example countVowels("ABCDE") => 2 * @example countVowels("Hello") => 2 */ const countVowels = (str) => { 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 - for (let i = 0; i < str.length; i++) { - const char = str[i].toLowerCase() - if (vowels.has(char)) { - count++ - } - } - return count + + const vowelRegex = /[aeiou]/gi; + const vowelsArray = str.match(vowelRegex) || []; + + return vowelsArray.length; } -export { countVowels } +export { countVowels };