-
Notifications
You must be signed in to change notification settings - Fork 18
/
3.oo-one-class.js
73 lines (63 loc) · 1.86 KB
/
3.oo-one-class.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/*
This program is a refactoring of program 2 into a class - in object-oriented
programming terms. It converts the functions in program 2 into methods, and uses
a static method "main()" to kick-off the program.
*/
"use strict"
const fs = require('fs');
class WordCount {
// the constructor takes in the location of the file, os that
// later we can easily use this on other files
constructor(filepath) {
this.filepath = filepath;
}
// returns the content of the file as a string
content() {
return fs.readFileSync(this.filepath).toString();
}
// returns the contents as an array of words
words() {
return this.content().split(/[\s.,\/:\n]+/);
}
// returns a tally object, as tallyUp in program 2 does
tally() {
let words = this.words();
let tally = {};
for (let i = 0; i < words.length; i++) {
let word = words[i].toLowerCase();
tally[word] = (tally[word] || 0) + 1;
}
return tally;
}
// returns the top 10 words as an array, as getTop10 does
// in program 2
top10() {
let tally = this.tally();
let tallyAsArray = [];
for (let word in tally) {
tallyAsArray.push({ word: word, count: tally[word] });
}
tallyAsArray.sort(function(one, other) {
return other.count - one.count;
});
return tallyAsArray.slice(0, 10);
}
// prints the top 10 words as printTop10 does in
// program 2
printTop10() {
let top10 = this.top10();
console.log('The top 10 most frequently used:');
console.log('--------------------------------');
for (let i = 0; i < top10.length; i++) {
let rank = i + 1;
let entry = top10[i];
console.log(rank + '. ' + entry.word + ': ' + entry.count);
}
}
// the main entry point of the program, to be called below
static main() {
let tally = new WordCount('words.txt');
tally.printTop10();
}
}
WordCount.main();