mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-06 01:18:23 +08:00
Merge pull request #432 from josecarlosweb/feat/Add_MaxCharacter_algoritm
Added max character algorithm
This commit is contained in:
29
String/MaxCharacter.js
Normal file
29
String/MaxCharacter.js
Normal 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 }
|
12
String/MaxCharacter.test.js
Normal file
12
String/MaxCharacter.test.js
Normal 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')
|
||||
})
|
||||
})
|
Reference in New Issue
Block a user