Skip to content

Instantly share code, notes, and snippets.

@amundo
Last active August 29, 2015 14:07
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 amundo/f8b4755f8fc46e1e82b0 to your computer and use it in GitHub Desktop.
Save amundo/f8b4755f8fc46e1e82b0 to your computer and use it in GitHub Desktop.
counting things in javascript
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 }
@amundo
Copy link
Author

amundo commented Oct 19, 2014

There’s probably a better way to initialize the tally object than

if (!(item in tally)) {
  tally[item] = 0
}
tally[item] += 1;

(This works more or less like a defaultdict in python.)

But I find the third line in things like this:

function count(arr){
  return arr.reduce(function(m,e){
    tally[item] = (+tally[item] || 0)+1; 
    return tally
  },{});
}

…difficult to read.

@amundo
Copy link
Author

amundo commented Oct 19, 2014

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.

@amundo
Copy link
Author

amundo commented Oct 19, 2014

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