Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 5ed4227

Browse files
Merge pull request TheAlgorithms#722 from farha1/master
Add max word algorithm
2 parents 00c616d + 30d437b commit 5ed4227

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

‎String/MaxWord.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
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 }

‎String/test/MaxWord.test.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
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+
})

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /