Merge pull request #432 from josecarlosweb/feat/Add_MaxCharacter_algoritm

Added max character algorithm
This commit is contained in:
Omkarnath Parida
2020-10-12 00:24:09 +05:30
committed by GitHub
2 changed files with 41 additions and 0 deletions

29
String/MaxCharacter.js Normal file
View File

@ -0,0 +1,29 @@
/*
Given a string of characters, return the character that appears the most often.
Example: input = "Hello World!" return "l"
*/
const maxCharacter = (value) => {
if (typeof value !== 'string') {
throw new TypeError('The param should be a string')
} else if (!value) {
throw new Error('The param should be a valid string')
}
const occurrences = {}
for (let i = 0; i < value.length; i++) {
const char = value[i]
if (/\s/.test(char)) continue
occurrences[char] = occurrences[char] + 1 || 1
}
let maxCharacter = null
let maxCount = 0
Object.keys(occurrences).forEach(char => {
if (occurrences[char] > maxCount) {
maxCount = occurrences[char]
maxCharacter = char
}
})
return maxCharacter
}
export { maxCharacter }

View File

@ -0,0 +1,12 @@
import { maxCharacter } from './MaxCharacter'
describe('Testing the maxCharacter function', () => {
it('Expect throw with wrong arg', () => {
expect(() => maxCharacter(123)).toThrow()
})
it('Check the max character in string', () => {
const theString = 'I can\'t do that'
const maxChar = maxCharacter(theString)
expect(maxChar).toBe('t')
})
})