index.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. 'use strict';
  2. var toPosInt = require('es5-ext/number/to-pos-integer')
  3. , create = Object.create, hasOwnProperty = Object.prototype.hasOwnProperty;
  4. module.exports = function (limit) {
  5. var size = 0, base = 1, queue = create(null), map = create(null), index = 0, del;
  6. limit = toPosInt(limit);
  7. return {
  8. hit: function (id) {
  9. var oldIndex = map[id], nuIndex = ++index;
  10. queue[nuIndex] = id;
  11. map[id] = nuIndex;
  12. if (!oldIndex) {
  13. ++size;
  14. if (size <= limit) return;
  15. id = queue[base];
  16. del(id);
  17. return id;
  18. }
  19. delete queue[oldIndex];
  20. if (base !== oldIndex) return;
  21. while (!hasOwnProperty.call(queue, ++base)) continue; //jslint: skip
  22. },
  23. delete: del = function (id) {
  24. var oldIndex = map[id];
  25. if (!oldIndex) return;
  26. delete queue[oldIndex];
  27. delete map[id];
  28. --size;
  29. if (base !== oldIndex) return;
  30. if (!size) {
  31. index = 0;
  32. base = 1;
  33. return;
  34. }
  35. while (!hasOwnProperty.call(queue, ++base)) continue; //jslint: skip
  36. },
  37. clear: function () {
  38. size = 0;
  39. base = 1;
  40. queue = create(null);
  41. map = create(null);
  42. index = 0;
  43. }
  44. };
  45. };