Boss lesson · Unit 05
A log report
Parse lines of text into records, then count, group and rank them
What you practise
- Lines of text parsed into typed records, then counted, grouped and ranked into a report
Try a question from this lesson
Pick one
A server writes one line per event: a time, a level, and what it was about. What does this print for one line?
const line = "09:02 ERROR db";
const parts = line.split(" ");
console.log(parts.length, parts[1]);Correct answer
3 ERROR
Why
Splitting at the spaces gives three pieces: "09:02", "ERROR" and "db". Index 1 is the middle one. A log line is text with a fixed layout, and split is how you get at the parts.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
The plan: text, records, answers
The job: read log lines and report which problem happens most.
Working on raw text all the way is painful. So parse each line once into a typed record, an Entry. From then on the compiler knows every property, and every question ("how many errors?", "which is most common?") is a short chain of array methods.
type Entry = {
time: string;
level: string;
msg: string;
};
// "09:02 ERROR db" becomes
// { time: "09:02", level: "ERROR",
// msg: "db" }Concept
Counting by group
"How many of each?" needs one counter per group. A Record<string, number> holds them: the key is the group, the value is its count.
Walk the list. The first time a key shows up it has no count yet, so reading it gives undefined: start it at 0. Then add one.
const levels = ["INFO", "ERROR", "ERROR"];
const counts: Record<string, number> = {};
for (const level of levels) {
if (counts[level] === undefined) {
counts[level] = 0;
}
counts[level] += 1;
}
console.log(counts.INFO, counts.ERROR);
// 1 2Concept
Ranking the groups
Counts sit in an object, and an object cannot be sorted. Object.entries turns it into an array of [key, value] tuples, and arrays can.
In each tuple, index 0 is the key and index 1 is the count. Sort by index 1, largest first, and the winner is at the front.
const counts = { db: 3, mail: 1, web: 2 };
const pairs = Object.entries(counts);
// [["db", 3], ["mail", 1], ["web", 2]]
pairs.sort((a, b) => b[1] - a[1]);
console.log(pairs[0][0]); // db
console.log(pairs[2][0]); // mail9 more exercises in the app
- 2× fill the blanks
- 3× type the answer
- 2× multiple choice
- 1× order the lines
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.