Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions String/MaxCharacter.js
Original file line number Diff line number Diff line change
@@ -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 }
12 changes: 12 additions & 0 deletions String/MaxCharacter.test.js
Original file line number Diff line number Diff line change
@@ -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')
})
})