Skip to content

Instantly share code, notes, and snippets.

@filip505
Created January 21, 2020 13:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save filip505/60fcc0e2eb1dd3bd510db7b5d1647640 to your computer and use it in GitHub Desktop.
Save filip505/60fcc0e2eb1dd3bd510db7b5d1647640 to your computer and use it in GitHub Desktop.
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