Start learning free

LESSON 382 OF 414 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: wc v2 — Count Words in TypeScript

Practice

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

    Wc V2 in TypeScript

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