Reputation: 13
This code works, but I was wondering if it was possible to receive some advice on how to make this function run faster.
I have used regular expressions as well as the match method because they seem straightforward to me.
const vowelCount = str => {
let vowels = /[aeiou]/gi;
let result = str.match(vowels);
let count = result.length;
console.log(count);
};
The function will display the number of vowels inside a string.
Upvotes: 1
Views: 276
Reputation: 3408
A simple for loop or foreach is marginally faster but it is so minor that you aren't really looking at much benefit by moving here.
However here are some faster options.
Your Code (timed): ~0.185 ms
const vowelCount = str => {
let vowels = /[aeiou]/gi;
let result = str.match(vowels);
return result.length;
};
var t0 = performance.now();
vowelCount("aSdDDDdasDD");
var t1 = performance.now();
console.log("Call took: " + (t1 - t0) + " MS");
For-Loop (timed): ~.070 ms
const vowelCount = str => {
var vowels = 'aeiouAEIOU';
var count = 0;
for(var x = 0; x < str.length ; x++) {
if (vowels.indexOf(str[x]) !== -1){
count += 1;
}
}
return count;
};
var t3 = performance.now();
vowelCount("aSdDDDdasDD");
var t4 = performance.now();
console.log("Call took: " + (t4 - t3) + " MS");
For-Each (timed): ~.074 ms
const vowelCount = str => {
var vowels = 'aeiouAEIOU';
var count = 0;
Array.from(str).forEach((c) => {
if(vowels.indexOf(c)) {
count++;
}
});
return count;
};
var t3 = performance.now();
vowelCount("aSdDDDdasDD");
var t4 = performance.now();
console.log("Call took: " + (t4 - t3) + " MS");
Upvotes: 2