How to use a Set for O(1) Lookups In Javascript
Using a Set for O(1) lookups involves storing vowels in a Set, enabling efficient membership checks. This approach leverages the Set’s average constant-time complexity for checking if a character (converted to lowercase) is present, making it both clean and performant.
Example:
function isVowel(char) {
const vowels = new Set(['a', 'e', 'i', 'o', 'u']);
return char.length === 1 && vowels.has(char.toLowerCase());
}
console.log(isVowel('U'));
console.log(isVowel('p'));
console.log(isVowel('o'));
Output
true false true
JavaScript Program to Check if a Character is Vowel or Not
In this article, we will check if the input character is a vowel or not using JavaScript. Vowel characters are ‘a’, ‘e’, ‘i’, ‘o’, and ‘u’. All other characters are not vowels.
Examples:
Input : 'u'
Output : True
Explanation: 'u' is among the vowel characters family (a,e,i,o,u).
Input : 'b'
Output : False
Explanation: 'b' is not among the vowel characters family (a,e,i,o,u).
Table of Content
- Using includes() Method
- Using test() Method
- Using indexOf() Method
- Using if-else Statements
- Using a Switch Statement
- Using a Set for O(1) Lookups