Boss lesson · Unit 05
A log report
Parse lines of text, then count, group and rank
What you practise
- Lines of text parsed into records, then counted, grouped and ranked into a report
Try a question from this lesson
Pick one
A web server writes one line per request: method, path, status code, milliseconds. Which piece does this print?
const line = "GET /cart 500 340";
const parts = line.split(" ");
console.log(parts[2]);Correct answer
500
Why
Splitting at the spaces gives four pieces, and index 2 is the third one: the status code. Status 200 means the request went fine, and 500 and above mean the server failed.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
From text to records
A log file is one long string. The plan for this lesson:
1. Split the text into lines. 2. Split each line into pieces and build an object from them: a record. 3. Let the array methods count, group and rank the records.
Inside a string, \n is the invisible character that ends a line.
const text = "GET /a 200\nGET /b 500";
const lines = text.split("\n");
console.log(lines.length); // 2
console.log(lines[1]); // GET /b 500Concept
Counting by key
To count how often each path appears, use an object as a tally sheet: the path is the key, the count is the value.
The first time a path shows up, its key is missing, and a missing key gives undefined. That is falsy, so || 0 swaps in a 0 to start counting from.
const paths = ["/home", "/cart", "/home"];
const counts = {};
for (const p of paths) {
counts[p] = (counts[p] || 0) + 1;
}
console.log(counts["/home"]); // 2
console.log(counts["/cart"]); // 110 more exercises in the app
- 3× type the answer
- 2× fill the blanks
- 1× order the lines
- 2× multiple choice
- 1× true or false
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.