forked from airportyh/word-count
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclasses.js
55 lines (47 loc) · 1.32 KB
/
classes.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
"use strict";
class WordScore {
constructor(word) {
this.word = word;
this.score = 0;
}
increment() {
this.score++;
return this;
}
}
export class Tally {
constructor() {
this.tally = new Map();
}
getWordScore(word) {
const w = word.toLowerCase();
return this.tally.has(w) ? this.tally.get(w) : new WordScore(w);
}
addToTally(words) {
words.forEach((word) => {
const wordScore = this.getWordScore(word).increment();
this.tally.set(wordScore.word, wordScore);
});
return this;
}
getTop(n) {
const sortedWordScores = Array.from(this.tally.values())
.sort((a, b) => b.score - a.score);
return sortedWordScores.slice(0, Math.min(n, sortedWordScores.length));
}
}
function printTop(topWords) {
return [`The top ${topWords.length} most frequently used:`,
'--------------------------------']
.concat(topWords.map((wordScore, index) => `${index + 1}. ${wordScore.word}: ${wordScore.score}`))
.join("\n");
}
export default function main(content) {
const top10 = new Tally()
.addToTally(splitIntoWords(content))
.getTop(10);
return printTop(top10);
}
function splitIntoWords(text) {
return text.split(/[\W]+/);
}