I am trying to map the repetition of letters into a hashmap and then returning the first non-repeated character in a string. Following is the function I've written to do so:
export const firstNonRepeatedFinder = (aString: string): string | null => {
const lettersMap: Map<string, number> = new Map<string, number>();
for (let letter of aString) {
if (!lettersMap.has(letter)) {
lettersMap.set(letter, 1);
} else {
incrementLetterCount(letter, lettersMap);
}
}
for (let letter of aString) {
if (lettersMap.get(letter) === 1) return letter;
}
return null;
function incrementLetterCount(
aLetter: string,
aLettersHashMap: Map<string, number>
): void {
if (
aLettersHashMap.has(aLetter) &&
aLettersHashMap.get(aLetter) !== undefined
) {
aLettersHashMap.set(aLetter, aLettersHashMap.get(aLetter) + 1);
}
}
};
However, in incrementLetterCount
, function, although I am handling to exclude the undefined
values for getting a key
in the hashmap, it still complaining about Object is possibly 'undefined'
which means that the get
method is might return undefined and I cannot proceed with it.
Does anyone know what I am missing here that results in this error?
if (aLettersHashMap.has(aLetter) && aLettersHashMap.get(aLetter))
work? Just test its truthiness.else { aLettersHashMap.set(aLetter, 1); }
case that should do the initialization.if (aLettersHashMap.has(aLetter) && aLettersHashMap.get(aLetter))
is true. I am not sure if I fully understood the second comment. But do you mean that in the else statement I should have instantiated{ aLettersHashMap.set(aLetter, 1); }
? in more details:else { lettersMap.set(letter, 1); incrementLetterCount(letter, lettersMap); }
if so, this will always default theaLetter
counter to 1aLettersHashMap.get(aLetter)
has a value of1
when I console.log() it in the incrementation loop, before incrementing it, meaning that they are instantiated