Reduce a list of words to counts for each unique word.
Created
February 24, 2014 17:41
-
-
Save joyrexus/9193045 to your computer and use it in GitHub Desktop.
Use of reduce for word counting
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{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