Problem overview
The Unix cat command prints text. This first version of the project builds its simplest form. The method cat(lines) receives an array of strings and returns one string in which every line sits on its own row, so that printing the result shows one line per row.
For ["hello", "world", "foo"] the result is the string "hello\nworld\nfoo". Printed, it looks like this:
hello
world
foo
Lines can be blank, and the array can be empty. An empty array gives an empty string.
Approach: glue the lines with a separator
The output is one long string where a newline character, \n, separates each line from the next. Arrays have a method made for this: join(separator) returns a string with all elements in order and the separator between each two of them.
The key word is between. With three lines there are two separators, so the last line gets no newline after it. A loop that appends line + "\n" every time would leave a stray newline at the end, and join avoids that without any extra code.
A loop version would also work: start with an empty string, and for each line add a newline first unless it is the first line. It gives the same result with more code and an extra condition to get wrong, which is why join is the better tool here. The next version builds on this one.
Step by step
The lesson has a single step. Inside the cat method, return lines.join("\n"). The string "\n" is a single newline character: the backslash and the n in source code stand for one character, not two.
The solution in JavaScript
class Solution {
cat(lines) {
return lines.join("\n");
}
}
Seeing the result
The returned string and what it looks like when printed are two views of the same value. For ["a", "", "b"] the string has 4 characters: a, a newline, a newline, b. Passing it to console.log prints three rows, with the middle one empty:
a
b
Written as a string literal, with the newlines shown as escapes, the same value is "a\n\nb". Splitting it at "\n" gives back three elements.
Language details
joinwith no argument uses a comma.["hello", "world", "foo"].join()gives"hello,world,foo", so the"\n"must be written out.- Blank lines survive.
["a", "", "b"]becomes"a\n\nb": the empty string contributes no characters, but both separators around it stay, which makes a blank row when printed. - The method is declared inside a
class Solutionand called on an instance, as the lesson's tests do.
Edge cases and common mistakes
- Empty array.
[].join("\n")is"", so no special case is needed. - One line.
["only"]gives"only", with no separator at all. - A trailing blank line.
["a", ""]gives"a\n", a string that ends in a newline, because the blank line still counts as an element. - One blank line looks like nothing.
[""]and[]both give"". The result alone can't tell them apart.
Key takeaways
join(separator)puts the separator between elements only, never after the last.- The default separator is a comma, so pass
"\n"explicitly. - Empty and one-element arrays work without special cases.
