Last active
November 10, 2020 20:56
-
-
Save anushshukla/6c8b76c157f56a0cc9f75285eb7aa101 to your computer and use it in GitHub Desktop.
Get the most occurring character in a string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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