Now build the -n flag of the cat tool, as a new function. It prints every line preceded by its 1-based line number, right-aligned in 6 columns, then a tab character, then the line text. Blank lines are numbered too, and an empty list gives an empty string.
Function signature:
numberedCat(lines: string[]): string
Format per line: the line number right-aligned in a field 6 characters wide (padded with spaces on the left), then a literal tab (\t), then the original line.
Example:
Input: lines = ["hello", "world", "foo"]
Output:
" 1\thello\n 2\tworld\n 3\tfoo"
When printed:
1 hello
2 world
3 foo
Loop with an index, build each formatted line, then join them with
"\n". String.prototype.padStart handles the right-alignment in 6 columns.
For each index
i, build the line as String(i + 1).padStart(6, " ") + "\t" + lines[i], push it to an array, then return out.join("\n").
The full solution:
class Solution {
numberedCat(lines: string[]): string {
let out: string[] = [];
for (let i = 0; i < lines.length; i++) {
out.push(String(i + 1).padStart(6, " ") + "\t" + lines[i]);
}
return out.join("\n");
}
}
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
