/javascript/word-count/word-count.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var words = function(phrase) {
  var parts = phrase.split(/\s/);
  var count = {};
  parts.forEach(function(word) {
    if (!count.hasOwnProperty(word)) {
      count[word] = 1;
    } else {
      count[word]++;
    }
  });
  return count;
};

module.exports = words;

Comments

Wouldn't it be quicker to do split(' ') instead of using a reg exp?

AkA84 commented 8 January 2015 at 16:06 UTC

I don't know about performance - I imagine the regex match may be a little slower - whether or not that matters will depend on the context, but you do still have to take care of the newlines somehow.

helenst commented 9 January 2015 at 17:55 UTC

You're not logged in right now. Please login via GitHub to comment