Last active
August 29, 2015 14:07
-
-
Save amundo/f8b4755f8fc46e1e82b0 to your computer and use it in GitHub Desktop.
counting things in javascript
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
var count = function (sequence) { | |
return sequence.reduce(function (tally, item) { | |
if (!(item in tally)) { | |
tally[item] = 0 | |
} | |
tally[item] += 1; | |
return tally | |
}, { | |
}) | |
} | |
var words = 'pease porridge hot pease porridge cold pease porridge in the pot nine days old'.split(' '); | |
console.log(count(words)) | |
//{ pease: 3, porridge: 3, hot: 1, cold: 1, in: 1, the: 1, pot: 1, nine: 1, days: 1, old: 1 } | |
Anyway this whole business isn’t that much better than:
var count = function (sequence) {
var tally = {};
sequence.forEach(function (item) {
if (!(item in tally)) {
tally[item] = 0
}
tally[item] += 1;
})
return tally;
}
Except, I guess, that a reduce could be used in a function chain.
Brendan pointed out:
console.log(count('watch out for this'.split(' ')))
Object { watch: "function watch() {
[native code]
}1", out: 1, for: 1, this: 1 }
This is because Object.prototype
has a method called .watch()
in Firefox. Lame. So you can do this:
var count = function (sequence) {
return sequence.reduce(function (tally, item) {
if (!(tally.hasOwnProperty(item))) {
tally[item] = 0
}
tally[item] += 1;
return tally
}, {})
}
console.log(count('watch out for this'.split(' ')));
Which works, but then you write over .watch()
, which is deprecated anyway. But still. Lame.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There’s probably a better way to initialize the
tally
object than(This works more or less like a
defaultdict
in python.)But I find the third line in things like this:
…difficult to read.