Skip to content

Instantly share code, notes, and snippets.

@joyrexus
Created February 24, 2014 17:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joyrexus/9193045 to your computer and use it in GitHub Desktop.
Save joyrexus/9193045 to your computer and use it in GitHub Desktop.
Use of reduce for word counting

Reduce a list of words to counts for each unique word.

{deepEqual} = require 'assert'
counts = (words) ->
toCounts = (totals, word) ->
totals[word] ?= 0 # initialize if not yet totalsed
totals[word] += 1 # increment otherwise
totals
words.reduce toCounts, totals={}
words = ['a', 'a', 'b'] # words to count
expected = # expected result
a: 2
b: 1
deepEqual counts(words), expected
{deepEqual} = require 'assert'
counts = (words) ->
totals = {}
totals[w] = (totals[w] or 0) + 1 for w in words
totals
deepEqual counts(['a', 'a', 'b']),
a: 2
b: 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment