ref-counter.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // Reference counter, useful for garbage collector like functionality
  2. "use strict";
  3. var d = require("d")
  4. , extensions = require("../lib/registered-extensions")
  5. , create = Object.create, defineProperties = Object.defineProperties;
  6. extensions.refCounter = function (ignore, conf, options) {
  7. var cache, postfix;
  8. cache = create(null);
  9. postfix = (options.async && extensions.async) || (options.promise && extensions.promise)
  10. ? "async" : "";
  11. conf.on("set" + postfix, function (id, length) {
  12. cache[id] = length || 1;
  13. });
  14. conf.on("get" + postfix, function (id) {
  15. ++cache[id];
  16. });
  17. conf.on("delete" + postfix, function (id) {
  18. delete cache[id];
  19. });
  20. conf.on("clear" + postfix, function () {
  21. cache = {};
  22. });
  23. defineProperties(conf.memoized, {
  24. deleteRef: d(function () {
  25. var id = conf.get(arguments);
  26. if (id === null) return null;
  27. if (!cache[id]) return null;
  28. if (!--cache[id]) {
  29. conf.delete(id);
  30. return true;
  31. }
  32. return false;
  33. }),
  34. getRefCount: d(function () {
  35. var id = conf.get(arguments);
  36. if (id === null) return 0;
  37. if (!cache[id]) return 0;
  38. return cache[id];
  39. })
  40. });
  41. };