Start learning free

LESSON 600 OF 671 · PROJECTS: COMMAND-LINE TOOLS

cat v2 in JavaScript: Number Lines with padStart

Practice Read the full explanation

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)

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". JavaScript's 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 to an array, then return arr.join("\n").

The full solution:
class Solution {
    numberedCat(lines) {
        let out = [];
        for (let i = 0; i < lines.length; i++) {
            out.push(String(i + 1).padStart(6, " ") + "\t" + lines[i]);
        }
        return out.join("\n");
    }
}

STEP 1 OF 4
    Ctrl + Enter to check

    JAVASCRIPT · PROJECTS: COMMAND-LINE TOOLS

    Cat V2 in JavaScript, explained

    Problem overview

    This version adds the -n flag of cat as a new method, numberedCat(lines). Every line is printed with its 1-based line number first. The number is right-aligned in a field 6 characters wide, then comes a tab character, then the line itself. Blank lines are numbered too, and an empty array gives an empty string.

    For ["hello", "world", "foo"] the result is this string, shown with its escapes:

    "     1\thello\n     2\tworld\n     3\tfoo"

    Each number has five spaces in front of the 1, so the whole field is six characters wide.

    Approach: build one row per line, then join the rows

    The method needs the position of each line, so it loops with an index i that starts at 0. The line's number is i + 1, because numbering starts at 1. Each finished row is pushed onto an array, and the rows are joined with "\n", the same idea as in the first version, where the separator only goes between rows.

    The only new problem is the alignment. padStart(6, " ") returns a string at least 6 characters long, adding the given padding on the left. String(42).padStart(6) gives " 42".

    Step by step

    1. Create an empty array named out. It will hold the finished rows.
    2. Loop over the positions with for (let i = 0; i < lines.length; i++). The index is needed twice: for the number and to pick the line.
    3. Push one row per line. Turn i + 1 into text with String(), pad it to 6 characters, add "\t", then add the original line.
    4. Return out.join("\n") after the loop, so there is no newline after the last row.

    The solution in JavaScript

    class Solution {
        numberedCat(lines) {
            let out = [];
            for (let i = 0; i < lines.length; i++) {
                out.push(String(i + 1).padStart(6, " ") + "\t" + lines[i]);
            }
            return out.join("\n");
        }
    }

    Language details

    • padStart is a string method. Calling it on a number fails: const k = 5; k.padStart(6, " ") throws TypeError: k.padStart is not a function. That is why the number goes through String() first.
    • padStart never cuts a string. String(1234567).padStart(6, " ") returns "1234567", one character wider than the field. With the lesson's inputs that only matters from a million lines on.
    • "\t" is a single tab character, not four spaces.
    • The second argument of padStart is the padding text, and " " is also the default, so padStart(6) behaves the same.

    Testing

    With a blank line in the middle and with an empty array, the method returns:

    ["a","","b"] -> "     1\ta\n     2\t\n     3\tb"
    [] -> ""

    On twelve lines named l1 to l12, the rows from the ninth onward are:

    "     9\tl9"
    "    10\tl10"
    "    11\tl11"
    "    12\tl12"

    The numbers stay right-aligned when they gain a digit, which is the point of padding on the left.

    Edge cases and common mistakes

    • Starting the numbers at 0. The loop index is 0-based, the line number is i + 1.
    • Padding on the wrong side. padEnd would left-align the numbers.
    • Forgetting that blank lines count. A blank line is still an element, so it gets a number and an empty text after the tab, as " 2\t" above shows.
    • A trailing newline. Joining the rows, rather than appending "\n" to each, keeps the end of the string clean.
    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free