I have successfully implemented an array of vowels in C#, but I am unsure how to replicate this functionality in JavaScript.
Instead of directly translating your current algorithm into JavaScript, I think it would be more efficient to introduce a faster algorithm.
In general, using structures like Array
, ArrayList
, and List<T>
for "contains" tests is not ideal because it requires checking every value for a match (O(n)
time complexity). In contrast, structures like Hashtable (Dictionary<TKey,TValue>
) or HashSet<T>
offer constant time complexity (O(1)
) for "contains" operations.
Here is the proposed algorithm:
- Create a pre-defined set (in the mathematical sense) of known vowels.
- Iterate through each character in the string and check if the character exists in the set from step 1.
- (Based on your code, though not explicitly mentioned in your post, it appears you capitalize vowels in a new output string - this can be efficiently achieved using a StringBuilder instead of repeated string concatenation to improve performance).
Below is the implementation in C#:
String word = "hello, world.";
HashSet<Char> vowels = new HashSet<Char>( new[] { 'a', 'e', 'i', 'o', 'u' } );
StringBuilder output = new StringBuilder();
foreach( Char c in word )
{
if( vowels.Contains( c ) ) sb.Append( Char.ToUpper( c ) );
else sb.Append( c );
}
JavaScript does not have a HashSet<T> type (UPDATE: It is now available), nor does it support individual Char
values (only single-character strings returned by string.charAt
). In JavaScript, all Object
2 values act as keyed dictionaries with ideally constant lookup time by name - thus an Object can be used to store vowels as keys with dummy values, allowing iteration through each character in the string. Unfortunately, JavaScript lacks a StringBuilder, so string concatenation with +=
must suffice (although some JS environments optimize this internally with StringBuilder-like features, it is not part of the ECMAScript language spec):
var vowels = { 'a': 0, 'e': 0, 'i': 0, 'o': 0, 'u': 0 };
var word = "hello, world.";
var output = "";
for( var i = 0; i < word.length; i++ ) {
var c = word.charAt( i );
if( c in vowels ) { // this operation is O(1)
// character is a vowel
output += c.toUpperCase();
}
else {
output += c;
}
}
2: The JavaScript Object
and .NET's System.Object
are unrelated entities despite sharing the same name. In .NET, it is a superclass for reference types, while in JavaScript, it functions as a collection structure with key/value pairs.