Start learning free

LESSON 374 OF 410 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: head v2 — First n Lines in JavaScript

Practice

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, n)

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, n) {
        return lines.slice(0, n).join("\n");
    }
}

STEP 1 OF 1
    Ctrl + Enter to check

    Head V2 in JavaScript

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