Start learning free

LESSON 607 OF 675 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: head v1 — First 10 Lines

Practice

Build a tiny version of the Unix head command. Given a list of lines, return the first 10 lines joined by newline characters (\n). If the input has fewer than 10 lines, return all of them. If there are no lines at all, return the empty string.

Function signature:

head(lines: string[]): string

Example:

Input: lines = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"]

Output: "a\nb\nc\nd\ne\nf\ng\nh\ni\nj"

When printed:
a
b
c
d
e
f
g
h
i
j

Grab the first 10 elements of the array, then call join("\n") on the result. TypeScript's Array.prototype.slice is safe even when the array is shorter.

Use lines.slice(0, 10).join("\n") — slice caps the upper bound automatically.

The full solution:
class Solution {
    head(lines: string[]): string {
        return lines.slice(0, 10).join("\n");
    }
}

STEP 1 OF 1
    Ctrl + Enter to check