Start learning free

LESSON 12 OF 70 · PROJECTS: COMMAND-LINE TOOLS

wc with a Mode Flag in TypeScript

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: string[], mode: string): string

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: number = lines.length;
let numWords: number = 0;
let numChars: number = 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: string[], mode: string): string {
        let numLines: number = lines.length;
        let numWords: number = 0;
        let numChars: number = 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

    TYPESCRIPT · PROJECTS: COMMAND-LINE TOOLS

    Wc V4 in TypeScript, explained

    Problem overview

    The fourth version of the wc project merges the earlier ones. wc(lines: string[], mode: string): string computes the line, word and character counts and returns the one the mode asks for, as a string:

    • "l" returns the number of lines.
    • "w" returns the number of words.
    • "c" returns the number of characters, as the sum of the line lengths with no newlines.
    • "all" returns lines, words and characters joined by tab characters.

    Any other mode, such as "x" or "L", behaves like "all": modes are case-sensitive. For ["hello", "world"] with mode "all" the result is the string "2\t2\t10". For an empty array, "l", "w" and "c" give "0", and "all" gives "0\t0\t0".

    Approach: count everything once, then choose

    One option is to branch on the mode first and run only the loop that is needed. The lesson takes a simpler route: compute all three numbers in a single pass, then pick what to return. It costs a little extra work when only one count is wanted, but the code has one loop and the mode check stays at the end, where it is easy to read.

    The number of lines needs no loop at all, because it is the array's length. Words and characters are running totals, built exactly as in the previous two versions.

    This structure also shows how small programs grow. The three earlier versions each answered one question. Here the same loop bodies share one loop, and the new work is only the decision at the end: which of the stored numbers to hand back, and in what form.

    Step by step

    1. numLines. Store lines.length in a let typed number.
    2. numWords. A number that starts at 0.
    3. numChars. Another number starting at 0.
    4. Loop over the lines with for (const line of lines).
    5. Add the words. Trim the line, split on /\s+/, filter out empty pieces and take the length. The filter matters because "".split(/\s+/) is [""], one empty piece, which would otherwise count as a word.
    6. Add the characters. line.length includes spaces and tabs.
    7. Mode "l". After the loop, return String(numLines) if the mode is "l". The function returns text, so a number has to be converted.
    8. Mode "w". The same with numWords.
    9. Mode "c". The same with numChars.
    10. Everything else. The last line returns all three counts joined with tabs. It is reached for "all" and for any mode that was not matched above, which is exactly what the specification wants.

    The solution in TypeScript

    class Solution {
        wc(lines: string[], mode: string): string {
            let numLines: number = lines.length;
            let numWords: number = 0;
            let numChars: number = 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 worth a look:

    • === compares strings by content, and it is the usual choice in TypeScript. mode === "l" is false for "L", which is why uppercase modes fall through to the last line.
    • String(n) converts a number to its text form. The result type is string, so returning a bare number would be a type error. The compiler reports it, and the returned value would still be a number at run time, because types are erased, so a test that expects "3" would not get it.
    • In the last line, numLines + "\t" + numWords + ... works because + with a string on one side turns the number into text. The first + already has a string on its right, so no numeric addition happens. Be careful when no string is involved: 1 + 2 + "\t" + 3 gives "3\t3", because the first two numbers are added.
    • "\t" is one tab character, so "2\t2\t10" has three fields.

    Tracing one call

    Take lines = ["hello world", "foo bar baz", ""] and mode = "w". Before the loop, numLines is 3 and the other two totals are 0. The first line adds 2 words and 11 characters. The second adds 3 words and 11 characters. The empty line adds 0 words, because its split-and-filter chain ends with an empty array, and 0 characters. After the loop the totals are 5 words and 22 characters. The first if fails because the mode is not "l", the second succeeds, and the method returns "5".

    Complexity

    A single pass over the lines does all the work, and each character is handled a constant number of times, so the time is O(n) for n characters in total. The extra space is O(1) beyond the temporary pieces of one line.

    Edge cases and common mistakes

    • Returning a number. Each count must go through String(...). In "all" mode the + operators do it implicitly.
    • Unknown modes. "x" and "L" do not raise an error. They produce the same tab-separated text as "all". Checking mode === "all" and then returning something else for the leftovers would break that rule.
    • Empty list. The loop never runs, so the counts stay 0: "l" gives "0" and "all" gives "0\t0\t0".
    • Blank lines. A blank line still counts as a line in "l", adds 0 words and adds 0 characters.

    Testing

    Take lines = ["hello world", "foo bar baz", ""], which has 3 lines, 5 words and 22 characters (11, 11 and 0):

    modeResult
    "l""3"
    "w""5"
    "c""22"
    "all""3\t5\t22"
    "x""3\t5\t22"

    With []: mode "l" gives "0" and mode "all" gives "0\t0\t0".

    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free