-
Notifications
You must be signed in to change notification settings - Fork 40
/
async-all-word-count.js
70 lines (52 loc) · 2.11 KB
/
async-all-word-count.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
/*
----- unnecessary background story -----
Your grade school Math teacher visited you at Hack Reactor, expecting
you to do an old assignment to see if you're still a smart cookie.
In fact, your teacher expects you to do this every week to make sure
you keep practiced! How frustrating!
The assignment: Count the number of distinct words in a paragraph and
submit it to her.
However, you now have the power of code to do it within an instant and
can do it in a fraction of a second without her knowing :)
----- end of unnecessary background story -----
Write a function that reads an input file and outputs a .txt file
containing the word count of every word in your input.txt.
This is purely to practice use of asynchronous functions!
See exampleOutput folder's sampleOutput.txt for what your output should look like
with the given input.txt
Constraints:
1) No punctuation will be in your paragraph
2) This is case-insensitive, so apple and Apple both count as the same word
Allowed documentation:
- Node.js documentation for FS library (https://nodejs.org/api/fs.html)
/* */
const fs = require('fs');
// countWords is a helper function... it helps you convert a paragraph into
// the string you need
// EXAMPLE USAGE
// countWords('hello world Hello me') --> 'hello: 2\nme:1\nworld: 1\n'
const countWords = function(paragraph) {
let words = paragraph.trim('.').split(' ');
let wordBank = {};
for (let i = 0; i < words.length; i++) {
let word = words[i].toLowerCase();
if (wordBank.hasOwnProperty(word)) {
wordBank[word] += 1;
} else {
wordBank[word] = 1;
}
}
let outputString = '';
let wordsFound = Object.keys(wordBank).sort();
wordsFound.forEach(word => {
outputString += `${word}: ${wordBank[word]}\n`;
})
return outputString;
}
// inputFile: paragraph to read
// outputFile: path to write resulting txt file to
// EXAMPLE USAGE
// countAllWords('./input.txt', './output.txt') --> should output a .txt file in same directory
var countAllWords = function(inputFile, outputFile) {
/* WRITE CODE HERE */
}