Skip to content

Instantly share code, notes, and snippets.

@anushshukla
Last active November 10, 2020 20:56
Show Gist options
  • Select an option

  • Save anushshukla/6c8b76c157f56a0cc9f75285eb7aa101 to your computer and use it in GitHub Desktop.

Select an option

Save anushshukla/6c8b76c157f56a0cc9f75285eb7aa101 to your computer and use it in GitHub Desktop.
Get the most occurring character in a string
String.prototype.getHighestRepeatingChar = function() {
const charCountHash = {}
let highestOccurence = 0;
let highestRepeatingChar;
for (let charIndex = 0; charIndex < this.length; charIndex++) {
const currentChar = this[charIndex]
const prevCharCount = charCountHash[currentChar] || 0
const currentCharCount = prevCharCount + 1;
charCountHash[currentChar] = currentCharCount;
if (highestOccurence === 0) {
highestOccurence = 1;
highestRepeatingChar = currentChar;
}
if (currentCharCount > highestOccurence) {
highestOccurence = currentCharCount;
highestRepeatingChar = currentChar;
}
}
return highestRepeatingChar;
}
sample = 'testing ground is growling when tesla test is tried out';
console.log(`Most repeating character in "${sample}" is "${sample.getHighestRepeatingChar()}"`)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment