Skip to content

Instantly share code, notes, and snippets.

@brignano
Last active December 14, 2020 05:57
Show Gist options
  • Save brignano/e59fd56fde0092337b537ab25f731626 to your computer and use it in GitHub Desktop.
Save brignano/e59fd56fde0092337b537ab25f731626 to your computer and use it in GitHub Desktop.
count character occurrence in a word
function strLetterCount(word) {
/**
* initialize new key value pair (Map) where;
* key = character
* value = count
*/
let characterCounts = new Map();
/**
* loop through each character in the word
*/
for (let i = 0; i < word.length; i++) {
/**
* get the value (count) that is currently stored in our Map for the key (character)
* if we can't find the value, we will default the value (count) to 0
*/
let characterCount = characterCounts.get(word[i]) ?? 0;
/**
* take the current value (count) we retrieved from our map
* for the key (character) we are currently iterating over
* and add 1 to the count so it includes the current iteration
*/
characterCounts.set(word[i], characterCount + 1);
}
/**
* now we have completed the creation of our key value pair (Map)
* that will have a key for each character in the input word and
* an associated value or count equal to the number of occurrences
* for that character
*
woof =
{ key: w, value: 1 },
{ key: o, value: 2 },
{ key: f, value: 1 }
*
*/
/**
* initialize an empty string that will be our output from this method
*/
let outputString = '';
/**
* for each [character, count] pair in our character counts map we
* should append the character and count to our output stream
*/
for (const [character, count] of characterCounts.entries()) {
outputString += character + count;
}
/**
* finally we will return our output string
*/
return outputString;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment