Created
January 21, 2020 13:08
-
-
Save filip505/60fcc0e2eb1dd3bd510db7b5d1647640 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var fs = require("fs") | |
var text = fs.readFileSync("./data.txt") | |
.toString() | |
.toLowerCase() | |
.replace(/[^\w\s]/gi, '') | |
.split("\n") | |
var parsed = {} | |
// in production I would devide this part into countWords function | |
for (var sentence of text) { | |
words = sentence.split(' ') | |
for (var word of words) { | |
if (parsed[word] && word) | |
parsed[word] = parsed[word] + 1 | |
else | |
parsed[word] = 1 | |
} | |
} | |
const res = Object.entries(parsed) | |
.sort((x, y) => x[1] > y[1] ? -1 : 0) // in production I would devide this function callback into seperated sortByNumberOfWords function | |
.map((item) => `${item[0]} (${item[1]})`) // in production I would devide this function callback into seperated printRow function | |
.join('\n') | |
fs.writeFile("res.txt", res, function (err) { | |
if (err) { | |
return console.log(err); | |
} | |
console.log("The file was saved!"); | |
}); | |
// I would create unit test for each of devided function to make sure each of them is running correctly | |
// Please feel free to check my other coding challanges i did | |
// https://github.com/filip505/president | |
// https://github.com/filip505/omdb |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment