Start learning free

LESSON 6 OF 70 · PROJECTS: COMMAND-LINE TOOLS

head -n in TypeScript: First n Lines with slice

Practice Read the full explanation

Extend your head command to take an integer n and return the first n lines of lines, joined by newline characters (\n). For this version you may assume 0 ≤ n ≤ lines.length. If n is 0 the result is the empty string.

Function signature:

head(lines: string[], n: number): string

Example:

Input: lines = ["alpha", "beta", "gamma", "delta", "epsilon"], n = 3

Output: "alpha\nbeta\ngamma"

When printed:
alpha
beta
gamma

Same idea as v1, but the cap is now n instead of the constant 10. Take a slice of lines up to index n, then join with "\n".

lines.slice(0, n) returns the first n elements; chain .join("\n").

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

STEP 1 OF 1
    Ctrl + Enter to check

    TYPESCRIPT · PROJECTS: COMMAND-LINE TOOLS

    Head V2 in TypeScript, explained

    Problem overview

    Version 2 of head takes the number of lines as a parameter. The method is now head(lines: string[], n: number): string, and it returns the first n lines joined by newline characters. For this version the input guarantees 0 <= n <= lines.length. When n is 0, the result is the empty string.

    For ["alpha", "beta", "gamma", "delta", "epsilon"] and n = 3, the result is "alpha\nbeta\ngamma". The version before this one used a fixed count of 10; here the count is the second argument.

    Approach: replace the constant with n

    The idea is the same as before: cut the array down, then join. Only the cut changes. lines.slice(0, n) returns a new array with the items at indexes 0 up to, but not including, n, which is exactly the first n lines. Joining that array with "\n" gives the answer.

    The special case n = 0 needs no code of its own. slice(0, 0) returns an empty array, and joining an empty array gives "".

    Here is the trace for the example. lines.slice(0, 3) is ["alpha", "beta", "gamma"], a new array with three items, and joining it gives "alpha\nbeta\ngamma". The original lines still holds all five entries afterwards.

    A for loop from 0 to n - 1 that pushes lines[i] onto a new array and then joins it gives the same result. The guarantee n <= lines.length is what makes that loop safe, since every lines[i] it reads exists. slice says the same thing in one expression and keeps the function to a single line.

    Step by step

    1. Return lines.slice(0, n).join("\n"). It is the previous version's line with n in place of 10.

    The solution in TypeScript

    class Solution {
        head(lines: string[], n: number): string {
            return lines.slice(0, n).join("\n");
        }
    }
    
    • Both parameters are typed: n: number is a plain number, and the compiler flags a string passed in its place. The types are erased in the compiled JavaScript, so nothing checks them while the program runs.
    • TypeScript has one number type for integers and decimals alike. Nothing in the type stops a caller from passing 2.7. slice drops the fractional part of its arguments, so slice(0, 2.7) returns the first 2 items. The lesson only uses whole numbers.
    • slice doesn't change lines.

    Calling the method on the example looks like this:

    const lines = ["alpha", "beta", "gamma", "delta", "epsilon"];
    console.log(new Solution().head(lines, 3));
    

    It prints three rows:

    alpha
    beta
    gamma

    The method returns the string and leaves the printing to the caller, which is why the result for n = 0 is an empty string rather than an empty line.

    Complexity

    Time and space are proportional to the size of the output: slice copies n items and join builds a string from them. Lines past index n are never looked at.

    Edge cases and common mistakes

    • n = 0. The result is "".
    • n equal to the number of lines. All lines come back: slice(0, 5) on five lines returns them all.
    • Empty list. The only allowed n is 0, and the result is "".
    • Wrong bounds. slice(1, n) skips the first line and slice(0, n - 1) returns one too few. The start is 0 and the end is n.
    • A trailing newline. None is added: join puts the separator between lines only.

    Testing

    InputResult
    ["alpha", "beta", "gamma", "delta", "epsilon"], n = 3"alpha\nbeta\ngamma"
    the same lines, n = 0""
    the same lines, n = 5"alpha\nbeta\ngamma\ndelta\nepsilon"
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free