I\'m supposed to write a function that takes a character (i.e. a string of length 1) and returns true if it is a vowel, false otherwise. I came up with two functions, but do
Personally, I would define it this way:
function isVowel( chr ){ return 'aeiou'.indexOf( chr[0].toLowerCase() ) !== -1 }
You could also use ['a','e','i','o','u']
and skip the length test, but then you are creating an array each time you call the function. (There are ways of mimicking this via closures, but those are a bit obscure to read)
I kind of like this method which I think covers all the bases:
const matches = str.match(/aeiou/gi];
return matches ? matches.length : 0;
I created a simplified version using Array.prototype.includes(). My technique is similar to @Kunle Babatunde.
const isVowel = (char) => ["a", "e", "i", "o", "u"].includes(char);
console.log(isVowel("o"), isVowel("s"));
This is a rough RegExp function I would have come up with (it's untested)
function isVowel(char) {
return /^[aeiou]$/.test(char.toLowerCase());
}
Which means, if (char.length == 1 && 'aeiou' is contained in char.toLowerCase()) then return true
.
benchmark
I think you can safely say a for loop is faster.
I do admit that a regexp looks cleaner in terms of code. If it's a real bottleneck then use a for loop, otherwise stick with the regular expression for reasons of "elegance"
If you want to go for simplicity then just use
function isVowel(c) {
return ['a', 'e', 'i', 'o', 'u'].indexOf(c.toLowerCase()) !== -1
}
cycles, arrays, regexp... for what? It can be much quicker :)
function isVowel(char)
{
return char === 'a' || char === 'e' || char === 'i' || char === 'o' || char === 'u' || false;
}