Start learning free

LESSON 376 OF 414 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: cat v4 — Concatenate Multiple Files in TypeScript

Practice

The real cat command can take many files as arguments and prints them one after another. Build that behavior. Given a list of "files" where each file is itself a list of lines, flatten all lines in order and join them with newlines.

A file can be empty (it adds no lines), and the list can hold no files at all; the result is then an empty string.

Function signature:

concatCat(allLines: string[][]): string

Example:

Input: allLines = [["hello", "world"], ["foo", "bar", "baz"]]

Output: "hello\nworld\nfoo\nbar\nbaz"

When printed:
hello
world
foo
bar
baz

Two steps: flatten the array of arrays into one flat array, preserving order. Then join with "\n".

You can use the built-in allLines.flat(), or do nested loops by hand:
for (let i = 0; i < allLines.length; i++) {
    for (let j = 0; j < allLines[i].length; j++) {
        flat.push(allLines[i][j]);
    }
}


The full solution:
class Solution {
    concatCat(allLines: string[][]): string {
        let flat: string[] = [];
        for (let i = 0; i < allLines.length; i++) {
            for (let j = 0; j < allLines[i].length; j++) {
                flat.push(allLines[i][j]);
            }
        }
        return flat.join("\n");
    }
}

STEP 1 OF 5
    Ctrl + Enter to check

    Cat V4 in TypeScript

    Keep going with TypeScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free