Skip to content

Commit 7ee564b

Browse files
authored
Merge pull request #432 from josecarlosweb/feat/Add_MaxCharacter_algoritm
Added max character algorithm
2 parents 3bb96cc + c751788 commit 7ee564b

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

String/MaxCharacter.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/*
2+
Given a string of characters, return the character that appears the most often.
3+
Example: input = "Hello World!" return "l"
4+
*/
5+
const maxCharacter = (value) => {
6+
if (typeof value !== 'string') {
7+
throw new TypeError('The param should be a string')
8+
} else if (!value) {
9+
throw new Error('The param should be a valid string')
10+
}
11+
12+
const occurrences = {}
13+
for (let i = 0; i < value.length; i++) {
14+
const char = value[i]
15+
if (/\s/.test(char)) continue
16+
occurrences[char] = occurrences[char] + 1 || 1
17+
}
18+
let maxCharacter = null
19+
let maxCount = 0
20+
Object.keys(occurrences).forEach(char => {
21+
if (occurrences[char] > maxCount) {
22+
maxCount = occurrences[char]
23+
maxCharacter = char
24+
}
25+
})
26+
return maxCharacter
27+
}
28+
29+
export { maxCharacter }

String/MaxCharacter.test.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import { maxCharacter } from './MaxCharacter'
2+
3+
describe('Testing the maxCharacter function', () => {
4+
it('Expect throw with wrong arg', () => {
5+
expect(() => maxCharacter(123)).toThrow()
6+
})
7+
it('Check the max character in string', () => {
8+
const theString = 'I can\'t do that'
9+
const maxChar = maxCharacter(theString)
10+
expect(maxChar).toBe('t')
11+
})
12+
})

0 commit comments

Comments
 (0)