Start learning free

LESSON 610 OF 671 · PROJECTS: COMMAND-LINE TOOLS

wc in JavaScript: Choosing What to Count with a Mode Flag

Practice Read the full explanation

Combine the previous three versions of wc. Given a list of lines and a mode flag, return the requested count(s) as a string. This is our own simplified interface, not the real wc flags: the real tool combines flags (such as -lw) and pads its columns with spaces.

Function signature:

wc(lines, mode)

Mode values:

  • "l" → line count, as a string.
  • "w" → word count (whitespace-separated tokens), as a string.
  • "c" → character count (lines only, no separating newlines), as a string.
  • "all" → lines + "\t" + words + "\t" + chars.

The "c" count is the one from v3 (the sum of the line lengths, no newlines). Any other mode value, for example "x" or "L" (modes are case-sensitive), gives the same result as "all". For an empty list, "l", "w" and "c" give "0" and "all" gives "0<TAB>0<TAB>0". The input is plain ASCII text.

Example:

Input: lines = ["hello", "world"], mode = "all"

Output: "2\t2\t10"

2 lines, 2 words (one per line), 10 characters total.


Compute all three counts in a single pass through lines, then branch on mode to pick the return value.

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;
}
Then String(numLines) / String(numWords) / String(numChars) as needed, or assemble all three with tabs.

The full solution:
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;
    }
}

STEP 1 OF 10
    Ctrl + Enter to check

    JAVASCRIPT · PROJECTS: COMMAND-LINE TOOLS

    Wc V4 in JavaScript, explained

    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

    1. Store the line count in numLines using the array's length. No loop is needed for it.
    2. Create numWords at 0. It will be filled by the loop.
    3. Create numChars at 0 for the same reason.
    4. Loop over the lines with for...of, naming each one line.
    5. 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.
    6. Add line.length to numChars. Spaces count and newlines are not part of the lines.
    7. Return String(numLines) for mode "l". The function returns text, never a number.
    8. Do the same for "w" with the word count.
    9. And for "c" with the character count.
    10. 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, so mode === "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:

    linenumWordsnumChars
    "hello world"211
    "foo bar baz"522
    ""522

    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

    linesmoderesult
    ["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"
    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free