Avatar of LearningNerd

LearningNerd's solution

to Word Count in the JavaScript Track

Published at Jul 13 2018 · 2 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

Setup

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

http://exercism.io/languages/javascript/installation

Running the test suite

The provided test suite uses Jasmine. You can install it by opening a terminal window and running the following command:

npm install -g jasmine

Run the test suite from the exercise directory with:

jasmine word-count.spec.js

In many test suites all but the first test have been marked "pending". Once you get a test passing, activate 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.spec.js

var Words = require('./word-count');

describe('count()', function () {
  var words = new Words();

  it('counts one word', function () {
    var expectedCounts = { word: 1 };
    expect(words.count('word')).toEqual(expectedCounts);
  });

  xit('counts one of each word', function () {
    var expectedCounts = { one: 1, of: 1, each: 1 };
    expect(words.count('one of each')).toEqual(expectedCounts);
  });

  xit('counts multiple occurrences of a word', function () {
    var expectedCounts = { one: 1, fish: 4, two: 1, red: 1, blue: 1 };
    expect(words.count('one fish two fish red fish blue fish')).toEqual(expectedCounts);
  });

  xit('handles cramped lists', function () {
    var expectedCounts = { one: 1, two: 1, three: 1 };
    expect(words.count('one,two,three')).toEqual(expectedCounts);
  });

  xit('ignores punctuation', function () {
    var expectedCounts = { car: 1, carpet: 1, as: 1, java: 1, javascript: 1 };
    expect(words.count('car : carpet as java: javascript!!&@$%^&')).toEqual(expectedCounts);
  });

  xit('includes numbers', function () {
    var expectedCounts = { testing: 2, 1: 1, 2: 1 };
    expect(words.count('testing 1 2 testing')).toEqual(expectedCounts);
  });

  xit('normalizes to lowercase', function () {
    var expectedCounts = { go: 3 };
    expect(words.count('go Go GO')).toEqual(expectedCounts);
  });

  xit('counts words with apostrophes', function () {
    var expectedCounts = { 'first': 1, 'don\'t': 2, 'laugh': 1, 'then': 1, 'cry': 1 };
    expect(words.count('First: don\'t laugh. Then: don\'t cry.')).toEqual(expectedCounts);
  });

  xit('counts words with quotations', function () {
    var expectedCounts = { 'joe': 1, 'can\'t': 1, 'tell': 1, 'between': 1, 'large': 2, 'and': 1 };
    expect(words.count('Joe can\'t tell between \'large\' and large.')).toEqual(expectedCounts);
  });

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

  xit('counts multiline', function () {
    var expectedCounts = { hello: 1, world: 1 };
    expect(words.count('hello\nworld')).toEqual(expectedCounts);
  });

  xit('counts tabs as white space', function () {
    var expectedCounts = { hello: 1, world: 1 };
    expect(words.count('hello\tworld')).toEqual(expectedCounts);
  });

  xit('counts multiple spaces as one', function () {
    var expectedCounts = { hello: 1, world: 1 };
    expect(words.count('hello  world')).toEqual(expectedCounts);
  });

  xit('does not count leading or trailing whitespace', function () {
    var expectedCounts = { introductory: 1, course: 1 };
    expect(words.count('\t\tIntroductory Course      ')).toEqual(expectedCounts);
  });

  xit('handles properties that exist on Object’s prototype', function () {
    var expectedCounts = { 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);
  });
});
var words = function(stringOfWords) {
	// splice the string using separators as any instance of 1 or more whitespace characters (\s)
	var arrayOfWords = stringOfWords.split(/\s+/);
	// create a wordCounts object without a prototype to prevent interference with reserved words like toString
	var wordCounts = Object.create(null);
	for (i = 0; i < arrayOfWords.length; i++) {
		var word = arrayOfWords[i];
		// if this word is not already a property of the wordCounts object, create it with the value of 1
		if (!wordCounts[word]) {
			wordCounts[word] = 1;
		} else {
		// if this word IS already a property of wordCounts, then increase its count value
			wordCounts[word]++;
		}
	}
	return wordCounts;
};

module.exports = words;

Community comments

Find this solution interesting? Ask the author a question to learn more.
Avatar of LearningNerd
LearningNerd
Solution Author
commented almost 5 years ago

I'm used to avoiding forEach because it isn't supported by older browsers, and to my eyes, simple for loops are more readable. But I realize my eyes have probably become old-fashioned, haha. Any feedback is welcome. :)

Avatar of gwmccull

I think both are pretty readable (for and forEach). ForEach naturally allows you to eliminate the var word = arrayOfWords[i]; line, which is kinda nice. It's supported by IE9 and above which is good enough for me :-)

BTW, thanks for the comment on another person's code regarding the Object.create(). It helped me refactor a couple lines out of my own code.

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?