Keep only the log lines that matter, using a list of levels declared once with as const.
What to build
A program that filters log lines by a minimum level and counts the lines of each level.
Requirements
- Declare
const LEVELS = ["DEBUG", "INFO", "WARN", "ERROR"] as constandtype Level = (typeof LEVELS)[number]. - Print each log line whose level is at least the minimum, unchanged.
- Then print
LEVEL: COUNTfor all four levels, in order, counting every valid line. - A line whose first word is not a level is not printed or counted; at the end print
bad lines: Kif there were any.
Input
Line 1: the minimum level. Line 2: n. Then n log lines LEVEL message.
Output
The kept lines, the four counts and possibly the bad line count.
Constraints
1 ≤ n ≤ 100; the minimum is a valid level.
Example
Input:
WARN
5
INFO server started
WARN disk 91% full
DEBUG cache hit
ERROR cannot write file
INFO request done
Output:
WARN disk 91% full
ERROR cannot write file
DEBUG: 1
INFO: 2
WARN: 1
ERROR: 1
Why it works
The order of the levels is written once, as data, and the type Level is derived from it, so the comparison and the type can never disagree about which levels exist.
Examples
Example 1 · Input
WARN 5 INFO server started WARN disk 91% full DEBUG cache hit ERROR cannot write file INFO request done
Expected output
WARN disk 91% full ERROR cannot write file DEBUG: 1 INFO: 2 WARN: 1 ERROR: 1
Example 2 · Input
DEBUG 3 debug lower case INFO ok TRACE too detailed
Expected output
INFO ok DEBUG: 0 INFO: 1 WARN: 0 ERROR: 0 bad lines: 2
Hints
Hint 1
Keep the levels in order in an array declared as const, and derive type Level from it.
Hint 2
A level is at least the minimum if its index in the array is at least the minimum's index.
Solution
Show one correct solution (try it yourself first)
const read = (): string => prompt() ?? "";
const LEVELS = ["DEBUG", "INFO", "WARN", "ERROR"] as const;
type Level = (typeof LEVELS)[number];
function isLevel(text: string): text is Level {
return (LEVELS as readonly string[]).includes(text);
}
const minimum = read();
const floor = LEVELS.indexOf(minimum as Level);
const counts: Record<Level, number> = { DEBUG: 0, INFO: 0, WARN: 0, ERROR: 0 };
let bad = 0;
const n = Number(read());
for (let i = 0; i < n; i++) {
const line = read();
const word = line.split(" ")[0];
if (!isLevel(word)) {
bad++;
continue;
}
counts[word]++;
if (LEVELS.indexOf(word) >= floor) console.log(line);
}
for (const level of LEVELS) console.log(level + ": " + counts[level]);
if (bad > 0) console.log("bad lines: " + bad);