Problem overview
The Unix wc command counts things in its input: lines, words and characters. The first version of the project builds only the line count. The method countLines(lines) receives an array of strings and returns how many lines it holds, as a number.
For ["hello", "world", "foo", "bar", "baz"] the answer is 5. Every entry is one line, even an empty string, and an empty array has 0 lines.
Approach: the array already knows its size
The input is already split into lines, one array element per line. Counting lines is therefore counting elements, and every array has a length property that holds exactly that number. No loop or counter is needed.
The statement's remark about empty strings matters. A blank line is still a line, so ["", "", ""] has 3 lines, not 0. Because the method counts elements and never looks at their contents, blank lines are counted correctly.
A counter loop would give the same number: start at 0, add 1 for each element, return the counter. It is longer and offers more places for an off-by-one slip, while length is maintained by the array itself and is always up to date, even after items are added or removed.
Step by step
The lesson has one step. Inside countLines, return lines.length.
The solution in JavaScript
class Solution {
countLines(lines) {
return lines.length;
}
}
Language details
lengthis a property, not a method, so it is written without parentheses.lines.length()throws aTypeError.- The returned value is a number, not a string, so it can be compared and added directly.
- For an empty array the value is
0. - The method counts the elements of the array. It does not count newline characters inside them:
["a\nb"]has one element, socountLinesreturns1, even though the text would print on two rows.
Using the method
The method lives in a class, so the code that tests it creates an instance first: after const s = new Solution();, the call s.countLines(["x", "", "y"]) returns 3, because the blank line counts. Try it in the editor above and print the result with console.log.
Testing
The method returns these results:
["hello","world","foo","bar","baz"] -> 5
["","",""] -> 3
[] -> 0
[""] -> 1
["a\nb"] -> 1
Edge cases and common mistakes
- Skipping blank lines. Filtering out empty strings before counting would give the wrong answer for
["", "", ""]. - Off-by-one counting. A loop that starts a counter at 1, or ends at
length - 1, is a common source of an answer that is off by one.lengthavoids it. - A single empty string.
[""]is one blank line, so the count is 1, not 0. - Counting text instead of an array. Splitting a string with
"a\nb\nc".split("\n")gives an array of 3 lines, and itslengthis 3. This version receives the array already split. A text that ends with a newline, such as"a\nb\n", splits into["a", "b", ""], which has 3 elements, so be aware of that final empty one when you split text yourself.
