collection.js 1.2 KB

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