Problem overview
The previous version of head(lines, n) assumed that n never exceeds the number of lines. This version drops that assumption: n can be larger than lines.length, and the method must then return all the lines. It must not crash and it must not pad the result. Here n is at least 0, and when n is 0 or there are no lines, the result is an empty string.
For ["alpha", "beta", "gamma"] with n = 10, the result is "alpha\nbeta\ngamma".
Approach: the code is already right
The one line from the previous version, lines.slice(0, n).join("\n"), handles this case unchanged. This lesson is about why it works.
slice(start, end) never reads past the end of the array. When end is bigger than the length, it behaves as if end were the length. So slice(0, 10) on three items returns the three items, with no undefined entries for the missing seven. Joining three items gives three lines and two newlines.
The alternative is to compute the cap yourself with Math.min(n, lines.length) and slice up to that. For the five lines "a" to "e" and n = 8, both versions return "a\nb\nc\nd\ne". The explicit cap makes the intent visible, but it adds nothing to the result.
Note what the answer does not do: it never invents lines. The result for a large n is the whole input, which is what the real head does when a file is shorter than the requested count.
Step by step
There is one step. Return lines.slice(0, n).join("\n"). Think of it as two independent guarantees. slice returns at most n items and never more than the array has. join turns any number of items, including none, into a string.
The solution in JavaScript
class Solution {
head(lines, n) {
return lines.slice(0, n).join("\n");
}
}
Language details
- Out-of-range indexes are handled differently by different array features. Reading
lines[10]on a 3-item array givesundefined, whilesliceclamps its bounds and returns only what exists. - Even an infinite end works:
slice(0, Infinity)on the five lines"alpha"to"epsilon"returns all five. - No new array is padded or extended. The result never has more items than the input.
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"], 5) 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
The method returns these results, where gr is the list ["alpha", "beta", "gamma", "delta", "epsilon"]:
["alpha","beta","gamma"], n = 10 -> "alpha\nbeta\ngamma"
gr, n = 8 -> "alpha\nbeta\ngamma\ndelta\nepsilon"
gr, n = 5 -> "alpha\nbeta\ngamma\ndelta\nepsilon"
[], n = 4 -> ""
gr, n = 0 -> ""
Edge cases and common mistakes
- Looping up to
n. Aforloop that readslines[i]fori < nwould collectundefinedfor a bign, andjoinwould turn each one into an empty string. Withn = 8on five lines, the loop result is"a\nb\nc\nd\ne\n\n\n", with extra blank rows at the end. Looping toMath.min(n, lines.length)avoids that. - Adding a guard that isn't needed. A check such as
if (n > lines.length)is harmless, but it duplicates whatslicedoes. - Empty input. An empty array gives
""for anyn. - n equal to the length. It is the boundary between the two versions, and it returns every line.
