Problem overview
The method wc(lines, mode) merges the three counters built so far (lines, words, characters) into one function. It takes an array of strings and a mode string, and always returns a string:
"l"gives the number of lines,"w"the number of words and"c"the number of characters, each converted to text."all"gives the three counts joined by tab characters, in the order lines, words, characters.- Any other mode, such as
"x"or"L", behaves like"all". Modes are case-sensitive.
For ["hello", "world"] with "all" the result is "2\t2\t10": 2 lines, 2 words, 10 characters. An empty array gives "0" for the single modes and "0\t0\t0" for "all".
Approach: count everything once, then pick
You could write four separate loops, one per mode, but the three counts are cheap and come from the same pass over the data. A better shape is to compute all three numbers first and only then decide what to return. The line count needs no loop at all, because it is lines.length. The word and character counts both grow inside a single for...of loop.
After the loop, a short chain of if statements handles the three single modes and returns early. Whatever is left, including "all" and every unknown mode, falls through to the last line, which builds the tab-separated string. That is how "anything else behaves like all" is implemented without listing the other modes.
The three if lines can come in any order, because each mode matches exactly one string. The default line must come last, though: it has no condition, so anything placed after it would never run.
The hard part of this lesson is not the counting, which earlier versions already practised, but the shape of the function: gather the data once, then make a decision. Programs with several output formats often take that shape, and it keeps the counting code from being repeated in every branch.
Step by step
- Store the line count in
numLinesusing the array'slength. No loop is needed for it. - Create
numWordsat 0. It will be filled by the loop. - Create
numCharsat 0 for the same reason. - Loop over the lines with
for...of, naming each oneline. - Add the line's word count to
numWords. Trim, split on/\s+/and filter out empty pieces. The filter matters because splitting an empty string gives[""], one empty piece, not zero pieces. - Add
line.lengthtonumChars. Spaces count and newlines are not part of the lines. - Return
String(numLines)for mode"l". The function returns text, never a number. - Do the same for
"w"with the word count. - And for
"c"with the character count. - Return the three counts joined by tabs as the last line. Every other mode ends up here.
The solution in JavaScript
class Solution {
wc(lines, mode) {
let numLines = lines.length;
let numWords = 0;
let numChars = 0;
for (const line of lines) {
numWords += line.trim().split(/\s+/).filter(x => x).length;
numChars += line.length;
}
if (mode === "l") return String(numLines);
if (mode === "w") return String(numWords);
if (mode === "c") return String(numChars);
return numLines + "\t" + numWords + "\t" + numChars;
}
}
Language details:
===compares without converting types, somode === "l"is true only for the exact string"l". This is what makes"L"fall through to the default.String(n)converts a number to its text form. It is the explicit version of what+does in the last line.- In
numLines + "\t" + numWords + "\t" + numChars, the first+has a number on the left and a string on the right, so JavaScript converts the number and concatenates. Every later+then works on a string. The expression never adds the numbers together. "\t"is a single tab character, so the result of"all"contains tabs, not the two characters backslash and t.
Tracing one run
Take lines = ["hello world", "foo bar baz", ""]. The line count is 3 straight away. The loop then updates the other two totals one line at a time:
| line | numWords | numChars |
|---|---|---|
"hello world" | 2 | 11 |
"foo bar baz" | 5 | 22 |
"" | 5 | 22 |
The empty line changes nothing: it has no words and no characters, but it still counts as a line. So mode "all" returns "3\t5\t22", while "l" returns "3". The line count and the word count differ because they measure different things, and a blank line is the clearest case.
Complexity
One pass over all characters does all the work, so the time is O(n) in the total text length, and the extra space is proportional to the longest line (the temporary word array). Computing all three counts even when only one is requested costs a constant factor, not a different order.
Edge cases and common mistakes
- Returning a number instead of a string for the single modes.
- Case handling.
"L"and"W"are not valid single modes here: they give the same tab-separated result as"all". - Counting an empty line as one word, which happens when the filter is missing.
- Wrong order in the tab string. It is lines, words, characters.
Testing
| lines | mode | result |
|---|---|---|
["hello", "world"] | "all" | "2\t2\t10" |
["hello world", "foo bar baz", ""] | "l" | "3" |
["hello world", "foo bar baz", ""] | "w" | "5" |
["hello world", "foo bar baz", ""] | "c" | "22" |
["hello", "world"] | "L" | "2\t2\t10" |
[] | "all" | "0\t0\t0" |
