Exercism v3 launches on Sept 1st 2021. Learn more! 🚀🚀🚀
Avatar of rootulp

rootulp's solution

to Word Count in the TypeScript Track

Published at Aug 11 2019 · 0 comments
Instructions
Test suite
Solution

Note:

This exercise has changed since this solution was written.

Given a phrase, count the occurrences of each word in that phrase.

For example for the input "olly olly in come free"

olly: 2
in: 1
come: 1
free: 1

Setup

Go through the setup instructions for TypeScript to install the necessary dependencies:

https://exercism.io/tracks/typescript/installation

Requirements

Install assignment dependencies:

$ yarn install

Making the test suite pass

Execute the tests with:

$ yarn test

In the test suites all tests but the first have been skipped.

Once you get a test passing, you can enable the next one by changing xit to it.

Source

This is a classic toy problem, but we were reminded of it by seeing it in the Go Tour.

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

word-count.test.ts

import Words from './word-count'

describe('words()', () => {
  const words = new Words()

  it('counts one word', () => {
    const expectedCounts = new Map(Object.entries({ word: 1 }))
    expect(words.count('word')).toEqual(expectedCounts)
  })

  xit('counts one of each', () => {
    const expectedCounts = new Map(Object.entries({ one: 1, of: 1, each: 1 }))
    expect(words.count('one of each')).toEqual(expectedCounts)
  })

  xit('counts multiple occurrences', () => {
    const expectedCounts = new Map(Object.entries({ one : 1, fish: 4, two: 1, red: 1, blue: 1 }))
    expect(words.count('one fish two fish red fish blue fish')).toEqual(expectedCounts)
  })

  xit('includes punctuation', () => {
    const expectedCounts = new Map(Object.entries({ car: 1, ':': 2, carpet: 1, as: 1, java: 1, 'javascript!!&@$%^&': 1 }))
    expect(words.count('car : carpet as java : javascript!!&@$%^&')).toEqual(expectedCounts)
  })

  xit('includes numbers', () => {
    const expectedCounts = new Map(Object.entries({ testing: 2, 1: 1, 2: 1 }))
    expect(words.count('1 2 testing testing')).toEqual(expectedCounts)
  })

  xit('normalizes to lower case', () => {
    const expectedCounts = new Map(Object.entries({ go: 3 }))
    expect(words.count('go Go GO')).toEqual(expectedCounts)
  })

  xit('counts properly international characters', () => {
    const expectedCounts = new Map(Object.entries({ '¡hola!': 1, '¿qué': 1, 'tal?': 1, 'привет!': 1 }))
    expect(words.count('¡Hola! ¿Qué tal? Привет!')).toEqual(expectedCounts)
  })

  xit('counts multiline', () => {
    const expectedCounts = new Map(Object.entries({ hello: 1, world: 1 }))
    expect(words.count('hello\nworld')).toEqual(expectedCounts)
  })

  xit('counts tabs', () => {
    const expectedCounts = new Map(Object.entries({ hello: 1, world: 1 }))
    expect(words.count('hello\tworld')).toEqual(expectedCounts)
  })

  xit('counts multiple spaces as one', () => {
    const expectedCounts = new Map(Object.entries({ hello: 1, world: 1 }))
    expect(words.count('hello  world')).toEqual(expectedCounts)
  })

  xit('does not count leading or trailing whitespace', () => {
    const expectedCounts = new Map(Object.entries({ introductory: 1, course: 1 }))
    expect(words.count('\t\tIntroductory Course      ')).toEqual(expectedCounts)
  })

  xit('handles properties that exist on Object’s prototype', () => {
    const expectedCounts = new Map(Object.entries({ reserved: 1, words : 1, like : 1,  constructor: 1, and : 1, tostring: 1,  'ok?': 1}))
    expect(words.count('reserved words like constructor and toString ok?')).toEqual(expectedCounts)
  })
})
export default class Words {
    public count(sentence: string): Map<string | number, number> {
        return this.getWords(sentence).reduce((counts: Map<string | number, number>, currentWord: string) => {
            const currentCountForWord = counts.get(currentWord)
            const newCountForWord = currentCountForWord ? currentCountForWord + 1 : 1
            counts.set(currentWord, newCountForWord)
            return counts
        }, new Map<string | number, number>())
    }

    private getWords(sentence: string): string[] {
        return this.removeMultipleSpaces(this.removeFormatting(sentence).split(" "))
    }

    private removeMultipleSpaces(words: string[]): string[] {
        return words.map((word) => word.trim()).filter((word) => word !== "")
    }

    private removeFormatting(sentence: string): string {
        return sentence.toLowerCase().replace("\n", " ").replace("\t", " ")
    }
}

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?