Skip to content

Instantly share code, notes, and snippets.

@goteusz-maszyk
Created November 16, 2022 14:49
Show Gist options
  • Save goteusz-maszyk/e15f90d06f8b41e9544002d19e21667d to your computer and use it in GitHub Desktop.
Save goteusz-maszyk/e15f90d06f8b41e9544002d19e21667d to your computer and use it in GitHub Desktop.
import { existsSync, readFileSync, createWriteStream, writeFileSync } from "fs";
const fileName = process.argv[2]
if (!existsSync(fileName)) {
console.log("Can't find file " + fileName)
process.exit(1)
}
const text = readFileSync(fileName, { encoding: 'utf-8' }).replace(/\r\n/g, "")
let totalLetters=0, totalLettersWithSpecialChars = 0
const letterCount = {}
const specialCharCount = {}
for (const i in text) {
const char = text[i]
totalLettersWithSpecialChars++
if (char.match(/[A-Za-zĀ-ňЀ-џ]/g)) {
totalLetters++
letterCount[char.toUpperCase()] = (letterCount[char.toUpperCase()] + 1) || 1
} else {
specialCharCount[char] = (specialCharCount[char] + 1) || 1
}
}
writeFileSync("./letter-summary.txt", "")
const writeStream = createWriteStream("./letter-summary.txt")
/**
* @param {String} text
* @param {Number} newLine 0-brak 1-tylko plik 2-zawsze
*/
function log(text, newLine) {
process.stdout.write(text + (newLine == 2 ? "\n" : ""))
writeStream.write(text + (newLine > 0 ? "\n" : ""))
}
const letters = Object.keys(letterCount).sort()
const specialChars = Object.keys(specialCharCount).sort()
log("Total letters: " + totalLetters, 2)
log("Total chars: " + totalLettersWithSpecialChars, 2)
log("Letter count:", 2)
for (const i in letters) {
const letter = letters[i]
const amount = letterCount[letter]
log(`${letter}: ${amount} (${Math.round(amount/totalLetters * 1000) / 10}%) `, 1)
}
log("\n\nLetter count with special chars:", 2)
for (const i in letters) {
const letter = letters[i]
const amount = letterCount[letter]
log(`${letter}: ${amount} (${Math.round(amount / totalLettersWithSpecialChars * 1000) / 10}%) `, 1)
}
const charNames = {
" ": "SPACE",
",": "COMMA",
";": "SEMICOLON",
":": "COLON",
".": "DOT"
}
for (const i in specialChars) {
const char = specialChars[i]
const amount = specialCharCount[char]
log(`${charNames[char] || char}: ${amount} (${Math.round(amount / totalLettersWithSpecialChars * 1000) / 10}%) `, 1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment