I'm attempting to create a mapping of repeated letters using a hashmap and then find the first non-repeated character in a string. Below is the function I've developed for this task:
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);
}
}
};
Despite handling the exclusion of undefined
values in the incrementLetterCount
function to get a key from the hashmap, an error message 'Object is possibly 'undefined'' is still appearing. This indicates that the get
method may return undefined, causing issues in the code execution.
Any ideas on what might be overlooked here leading to this error?