Exercism v3 launches on Sept 1st 2021. Learn more! ๐Ÿš€๐Ÿš€๐Ÿš€
Avatar of rootulp

rootulp's solution

to Word Count in the CoffeeScript Track

Published at Jul 13 2018 · 0 comments
Instructions
Test suite
Solution

Note:

This solution was written on an old version of Exercism. The tests below might not correspond to the solution code, and the exercise may have changed since this code 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

Refer to the Exercism CoffeScript page for getting started with CoffeeScript.

In order to run the test, you can run the test file from the exercise directory:

jasmine-node --coffee .

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.spec.coffee

Words = require "./words"

describe "Words", ->
  it "counts one word", ->
    words = new Words "word"
    expect(words.count()).toEqual
      word: 1

  xit "counts one of each", ->
    words = new Words "one of each"
    expect(words.count()).toEqual
      one: 1
      of: 1
      each: 1

  xit "counts multiple occurrences", ->
    words = new Words "one fish two fish red fish blue fish"
    expect(words.count()).toEqual
      one: 1
      fish: 4
      two: 1
      red: 1
      blue: 1

  xit "ignores punctuation", ->
    words = new Words "car : carpet as java : javascript!!&@$%^&"
    expect(words.count()).toEqual
      car: 1
      carpet: 1
      as: 1
      java: 1
      javascript: 1

  xit "includes numbers", ->
    words = new Words "testing, 1, 2 testing"
    expect(words.count()).toEqual
      testing: 2
      1: 1
      2: 1

  xit "normalizes case", ->
    words = new Words "go Go GO"
    expect(words.count()).toEqual
      go: 3
class Words
  constructor: (input) ->
    counts = {}
    words = input.toLowerCase().match(/\b[\w\d]+\b/g)

    for word in words
      counts[word] = if counts[word] then counts[word] + 1 else 1

    @count = counts
  module.exports = @

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?