Drill

ProblemsTypeScript › monitoring

Count log lines by level

mediummonitoringTypeScript

A log summariser reports how many lines came in at each level. The level is the first word on the line, and the file is not always tidy.

countByLevel(lines: list<string>) → map<string, int>

Solve it in the editor →

Where you start

function countByLevel(lines: string[]): Record<string, number> {
  
}

Worked examples

CallResult
countByLevel(["ERROR disk full","warn retrying","ERROR timeout"]){"ERROR":2,"WARN":1}
countByLevel(["INFO ok"]){"INFO":1}
countByLevel([""," "]){}
countByLevel(["DEBUG"]){"DEBUG":1}

Hint

Trim the line, take everything up to the first space, upper-case it.

Reference solution in TypeScript
function countByLevel(lines: string[]): Record<string, number> {
  const result: Record<string, number> = {};
  for (const line of lines) {
    const t = line.trim();
    if (t === "") continue;
    const level = t.split(/\s+/)[0].toUpperCase();
    result[level] = (result[level] || 0) + 1;
  }
  return result;
}

The same problem in another language

More monitoring problems in TypeScript