word-count.js in JavaScript
A complete word-frequency script: read a file, normalize, tally, report.
import { readFile } from "node:fs/promises";
import process from "node:process";
async function wordCount(path) {
const text = await readFile(path, "utf8");
const counts = new Map();
for (const raw of text.split(/\s+/)) {
const word = raw.replace(/[.,!?;:]/g, "").toLowerCase();
if (word) counts.set(word, (counts.get(word) || 0) + 1);
}
return [...counts.entries()].sort((a, b) => b[1] - a[1]);
}
const path = process.argv[2];
if (!path) {
console.error("usage: node word-count.js FILE");
process.exit(1);
}
for (const [word, count] of (await wordCount(path)).slice(0, 10)) {
console.log(String(count).padStart(6), word);
}
Keywords and builtins used here
MapStringasyncawaitconstforfromfunctionifimportofreturn
The run, in numbers
- Lines
- 21
- Characters to type
- 626
- Tokens
- 196
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 112 seconds.
Step 1 of 1 in Encore, step 43 of 43 in Language basics.