Start learning free

LESSON 8 OF 69 · PROJECTS: COMMAND-LINE TOOLS

head v4 in JavaScript: Negative n Drops the Tail

Practice Read the full explanation

Same signature as v2/v3, but now n may be negative. Real head -n -K prints all lines except the last K. So when n < 0 return all lines except the last |n|; when n ≥ 0 behave exactly like v3 (return the first n, capped at the input length). If |n| is at least the number of lines, nothing is left, so return the empty string.

Function signature:

head(lines, n)

Example (negative n):

Input: lines = ["a", "b", "c", "d", "e"], n = -2

Output: "a\nb\nc"

When printed:
a
b
c

JavaScript's slice(0, n) already does the right thing for both signs. A negative end index means "stop that many from the end".

The full solution is the same one-liner from v2/v3:
class Solution {
    head(lines, n) {
        return lines.slice(0, n).join("\n");
    }
}

STEP 1 OF 1
    Ctrl + Enter to check

    JAVASCRIPT · PROJECTS: COMMAND-LINE TOOLS

    Head V4 in JavaScript, explained

    Problem overview

    This version of head(lines, n) lets n be negative. The real head -n -K prints every line except the last K. So for a negative n, the method returns all lines except the last |n|. For n >= 0 it behaves as in the previous version: the first n lines, capped at the input length. If |n| is at least the number of lines, nothing is left and the result is an empty string.

    For ["a", "b", "c", "d", "e"] with n = -2, the last two lines are dropped and the result is "a\nb\nc".

    Approach: slice already understands negative ends

    The lesson's line is the same as in the last two versions, lines.slice(0, n).join("\n"), and this lesson shows why it also covers negative values. When the end index of slice is negative, it counts from the end of the array. An end of -2 means "stop 2 items before the end", which is the same as an end index of length - 2.

    That is exactly what head -n -2 asks for: keep everything up to the last two items. A negative end that reaches past the start of the array is clamped to 0, so the slice is empty. That covers "nothing is left" with no extra code.

    A hand-written version has to treat the sign explicitly. For a negative n, the end index is lines.length + n, but never below 0, so it needs Math.max(0, lines.length + n). For a positive n, the end is Math.min(n, lines.length). On the five lines "a" to "e", that version and the one-line version agree for n of -2, -5, -10, 3 and 9. The built-in behaviour of slice is simply that same logic.

    Step by step

    There is one step. Return lines.slice(0, n).join("\n"). A positive n keeps the first n items, a negative n keeps everything but the last |n|, and join makes the text, with "" for an empty result.

    The solution in JavaScript

    class Solution {
        head(lines, n) {
            return lines.slice(0, n).join("\n");
        }
    }

    Language details

    • Negative indexes work in slice, but not for reading an element: abc[-1] is undefined, while abc.at(-1) and abc.slice(-1) do count from the end.
    • Only the end index is negative in this lesson. slice(0, n) keeps the start fixed at 0.
    • -0 is handled like 0: slice(0, -0) is empty, and an empty array joins to "".

    Using the method

    The method lives in a class, so the code that tests it creates an instance first and then calls it. After const s = new Solution();, the call s.head(["a", "b", "c"], -1) returns "a\nb", and printing it shows a and b on two rows. Try it in the editor above and print the result with console.log, which shows the newlines as separate rows.

    Testing

    On the five lines "a" to "e", the method returns:

    n = -2 -> "a\nb\nc"
    n = -1 -> "a\nb\nc\nd"
    n = -4 -> "a"
    n = -5 -> ""
    n = -10 -> ""
    n = 2 -> "a\nb"
    n = 0 -> ""
    n = 9 -> "a\nb\nc\nd\ne"

    On an empty array with n = -3 the result is "".

    Edge cases and common mistakes

    • |n| equal to the length. n = -5 on five lines drops everything, and the result is "".
    • |n| bigger than the length. n = -10 on five lines also gives "". It never throws and never wraps around.
    • Using slice(n). With a negative single argument, slice(-2) keeps the last two items, the opposite of dropping them.
    • Branching by sign. A hand-written if (n < 0) version needs lines.length + n for the end index, plus a guard so it doesn't go below 0. slice does both.
    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free