Start learning free

LESSON 4 OF 70 · PROJECTS: COMMAND-LINE TOOLS

cat in TypeScript: Concatenate Several Files

Practice Read the full explanation

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

    TYPESCRIPT · PROJECTS: COMMAND-LINE TOOLS

    Cat V4 in TypeScript, explained

    Problem overview

    The real cat prints several files one after another. Version 4 models that with a function concatCat(allLines: string[][]): string. Each entry of allLines is one "file", itself an array of lines. The function puts all the lines in order, first file first, and joins them with newlines.

    For [["hello", "world"], ["foo", "bar", "baz"]] the result is "hello\nworld\nfoo\nbar\nbaz". A file can be empty and adds no lines. With no files at all the result is an empty string.

    Approach: flatten, then join

    The job has two parts. First turn the array of arrays into one flat array of lines, keeping the order. Then join that array with "\n", exactly as in version 1.

    Flattening needs a loop inside a loop. The outer loop visits each file, and the inner loop visits each line of that file and pushes it onto a flat array. Because the outer loop goes from the first file to the last, and the inner one from the first line to the last, the order comes out right.

    Joining once at the end matters: it puts newlines between lines, including the last line of one file and the first line of the next, and leaves none at the very end.

    Step by step

    1. Create an empty array flat of type string[]. It will hold every line of every file and has no arrays inside it.
    2. Loop over the files with i from 0 while i < allLines.length. Here allLines[i] is one file, an array of lines.
    3. Inside it, loop over the lines of that file with j from 0 while j < allLines[i].length.
    4. Push allLines[i][j] onto flat. An empty file never enters the inner loop, so it adds nothing.
    5. After both loops, return flat.join("\n"). This line sits outside the loops' braces, so it runs once after every file has been read.

    The solution in TypeScript

    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");
        }
    }
    
    • string[][] means an array whose elements are arrays of strings. allLines[i][j] reads the line at position j of file i.
    • The built-in allLines.flat() does the flattening in one call, and [[1, 2], [3]].flat() gives [1, 2, 3]. The nested loops show what that call does, and they work the same way.
    • The inner loop reads allLines[i].length for the current file, so files of different lengths are fine.

    Complexity

    If there are m files with L lines in total, the loops make m + L steps and the join copies every character once. Time is O(m + total length). Space is O(L) for flat, plus the result string.

    Edge cases and common mistakes

    • No files. [] gives "".
    • Empty files. [[], ["a"], [], ["b", "c"]] gives "a\nb\nc". Empty files add no lines and no extra newlines.
    • A file with one empty line. [[""], [""]] has two lines, both blank, so the result is "\n": one newline between two empty lines.
    • Mixing up the indexes. Writing allLines[j][i], or using i for both loops, reads the wrong element or goes past the end of an array.
    • Joining inside the loop. It would either put the newline in the wrong places or leave one at the end. Join once, after the loops.

    Testing

    InputResult
    [["hello", "world"], ["foo", "bar", "baz"]]"hello\nworld\nfoo\nbar\nbaz"
    [[], ["a"], [], ["b", "c"]]"a\nb\nc"
    [[""], [""]]"\n"
    []""
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free