UNPKG

840 BJavaScriptView Raw
1/**
2 * Push items and count them
3 */
4'use strict';
5
6function collection() {
7 this.items = {};
8}
9
10collection.prototype = {
11 push: function(item) {
12 if (typeof this.items[item] === 'undefined') {
13 this.items[item] = {
14 cnt: 1
15 };
16 } else {
17 this.items[item].cnt++;
18 }
19 },
20
21 sort: function() {
22 var newItems = {},
23 sortedKeys;
24
25 // sort in descending order (by cnt)
26 sortedKeys = Object.keys(this.items).sort((function(a, b) {
27 return this.items[b].cnt - this.items[a].cnt;
28 }).bind(this));
29
30 // build new items dictionary
31 sortedKeys.forEach(function(key) {
32 newItems[key] = this.items[key];
33 }, this);
34
35 this.items = newItems;
36 return this;
37 },
38
39 forEach: function(callback) {
40 Object.keys(this.items).forEach(function(key) {
41 callback(key, this.items[key].cnt);
42 }, this);
43 }
44};
45
46module.exports = collection;