File tree Expand file tree Collapse file tree 2 files changed +41
-0
lines changed Expand file tree Collapse file tree 2 files changed +41
-0
lines changed Original file line number Diff line number Diff line change 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 }
Original file line number Diff line number Diff line change 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+ } )
You can’t perform that action at this time.
0 commit comments