Start learning free

LESSON 10 OF 70 · PROJECTS: COMMAND-LINE TOOLS

wc -w in TypeScript: Counting Words in Lines

Practice Read the full explanation

Build a tiny version of the Unix wc -w command. Given a list of lines, return the total number of words (whitespace-separated tokens) across all lines as an integer.

Function signature:

countWords(lines: string[]): number

Example:

Input: lines = ["hello world", "foo bar baz", ""]

Output: 5

The empty string contributes 0 words, "hello world" contributes 2, and "foo bar baz" contributes 3. Total: 5.

Words are separated by one or more spaces or tabs, and leading or trailing whitespace is ignored. A line with no words (empty, or only whitespace) contributes 0, and an empty list of lines gives 0. The input is plain ASCII text.


Iterate over the lines, split on whitespace, and accumulate the count. Watch out for empty lines: they should contribute zero, not one.

Use line.trim().split(/\s+/).filter(x => x).length. The filter drops the empty token that split produces for empty strings.

The full solution:
class Solution {
    countWords(lines: string[]): number {
        let total = 0;
        for (const line of lines) {
            const tokens: string[] = line.trim().split(/\s+/).filter(x => x);
            total += tokens.length;
        }
        return total;
    }
}

STEP 1 OF 5
    Ctrl + Enter to check

    TYPESCRIPT · PROJECTS: COMMAND-LINE TOOLS

    Wc V2 in TypeScript, explained

    Problem overview

    This version of the wc project builds the word count, the job of wc -w. The method countWords(lines: string[]): number receives an array of lines and returns the total number of words in all of them. A word is a run of non-whitespace characters, and words are separated by one or more spaces or tabs.

    For ["hello world", "foo bar baz", ""] the answer is 5: two words, three words and none for the empty line. Leading and trailing whitespace is ignored, a line with only whitespace has no words, and an empty array gives 0.

    Approach: split each line, then add up the pieces

    The plan has two layers. For one line, cut it into words and count them. Over the whole array, add those counts into a running total. A for...of loop handles the outer layer, and a chain of three string and array methods handles the inner one.

    The inner layer has a trap. Splitting a string on a pattern does not give an empty array for an empty string. It gives one empty piece:

    "".split(/\s+/);          // [""]  (one piece, not zero)
    "  ".trim().split(/\s+/); // [""]
    " a b".split(/\s+/);     // ["", "a", "b"]  (leading whitespace gives an empty first piece)

    Counting the pieces without cleaning them up would make every blank line count as one word. Trimming the line first removes the leading and trailing whitespace pieces, and filtering removes the one empty piece that blank lines still produce.

    Step by step

    1. Create the total. Declare total with let and start it at 0. It changes as lines are read, so it can't be a const.
    2. Visit every line. A for (const line of lines) loop gives each string in turn. Everything that follows goes inside its braces.
    3. Cut the line into words. Call trim() to strip whitespace at both ends, split(/\s+/) to cut at every run of whitespace, and filter(x => x) to keep only the pieces that are not empty text. An empty string is falsy, so the filter drops it and keeps every real word. The result is stored in tokens, typed string[].
    4. Add the line's words. tokens.length is the number of words on this line, so add it to total.
    5. Return the total after the loop, once every line has been counted.

    The solution in TypeScript

    class Solution {
        countWords(lines: string[]): number {
            let total = 0;
            for (const line of lines) {
                const tokens: string[] = line.trim().split(/\s+/).filter(x => x);
                total += tokens.length;
            }
            return total;
        }
    }

    A few details are worth knowing:

    • /\s+/ is a regular expression literal. \s matches one whitespace character, including a space and a tab, and the + means "one or more", so a double space or a tab followed by a space is a single separator. Splitting on the plain string " " would not do this: "a b".split(" ") gives ["a", "", "b"], while "a b".split(/\s+/) gives ["a", "b"].
    • The filter callback x => x returns the string itself, and JavaScript treats the empty string as false and any other string as true. That is why it removes only empty pieces.
    • The annotation : string[] is a promise checked by the compiler. TypeScript erases it when it compiles to JavaScript, so it costs nothing at run time.
    • The return type is number, and a JavaScript number is a double, so counts stay exact for any realistic input.

    Complexity

    Every character of every line is looked at a constant number of times by trim, split and filter, so the time is O(n) where n is the total number of characters. Each line's pieces are built and thrown away before the next line, so the extra space is proportional to the longest line.

    Edge cases and common mistakes

    • Blank lines. Skipping the filter gives 1 for "" and for a line of only spaces. This is the most common bug in this lesson.
    • Skipping the trim. " a b".split(/\s+/) starts with an empty piece, so the line would count 3 words instead of 2. The filter would rescue that case too, but the trim states the intent clearly.
    • Tabs. Because the pattern is \s+, a line such as " a \t b " counts as 2 words.
    • No lines. With [] the loop never runs and the method returns 0.

    Testing

    InputResult
    ["hello world", "foo bar baz", ""]5
    [" a \t b ", " ", "x"]3
    []0

    The next version builds on this one.

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