File tree Expand file tree Collapse file tree 2 files changed +48
-0
lines changed Expand file tree Collapse file tree 2 files changed +48
-0
lines changed Original file line number Diff line number Diff line change 1+ // Given a sentence, return the most occuring word
2+
3+ /**
4+ * @param {string } sentence - the sentence you want to find the most occuring word
5+ * @returns {string } - the most occuring word
6+ *
7+ * @example
8+ * - maxWord('lala lili lala'); // lala
9+ */
10+ const maxWord = ( sentence = '' ) => {
11+ if ( typeof sentence !== 'string' ) {
12+ throw new TypeError ( 'the param sould be string' )
13+ }
14+
15+ if ( ! sentence ) {
16+ return null
17+ }
18+
19+ const words = sentence . split ( ' ' )
20+ if ( words . length < 2 ) {
21+ return words [ 0 ]
22+ }
23+
24+ const occurrences = { }
25+ words . forEach ( word => {
26+ occurrences [ word . toLocaleLowerCase ( ) ] = occurrences [ word . toLocaleLowerCase ( ) ] + 1 || 1
27+ } )
28+
29+ const max = Object . keys ( occurrences ) . reduce ( ( n , word ) => {
30+ if ( occurrences [ word ] > n . count ) { return { word, count : occurrences [ word ] } } else { return n }
31+ } , { word : '' , count : 0 } )
32+
33+ return max . word
34+ }
35+
36+ export { maxWord }
Original file line number Diff line number Diff line change 1+ import { maxWord } from '../MaxWord'
2+
3+ describe ( 'Testing the maxWord function' , ( ) => {
4+ it ( 'Expect throw with non string argument' , ( ) => {
5+ expect ( ( ) => maxWord ( 10 ) ) . toThrow ( )
6+ } )
7+ it ( 'get the max word' , ( ) => {
8+ const string = 'ba ba ba ba banana'
9+ const mostOccuringWord = maxWord ( string )
10+ expect ( mostOccuringWord ) . toBe ( 'ba' )
11+ } )
12+ } )
You can’t perform that action at this time.
0 commit comments