ref-counter.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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
  6. , defineProperties = Object.defineProperties;
  7. extensions.refCounter = function (ignore, conf, options) {
  8. var cache, postfix;
  9. cache = create(null);
  10. postfix =
  11. (options.async && extensions.async) || (options.promise && extensions.promise)
  12. ? "async"
  13. : "";
  14. conf.on("set" + postfix, function (id, length) { cache[id] = length || 1; });
  15. conf.on("get" + postfix, function (id) { ++cache[id]; });
  16. conf.on("delete" + postfix, function (id) { delete cache[id]; });
  17. conf.on("clear" + postfix, function () { cache = {}; });
  18. defineProperties(conf.memoized, {
  19. deleteRef: d(function () {
  20. var id = conf.get(arguments);
  21. if (id === null) return null;
  22. if (!cache[id]) return null;
  23. if (!--cache[id]) {
  24. conf.delete(id);
  25. return true;
  26. }
  27. return false;
  28. }),
  29. getRefCount: d(function () {
  30. var id = conf.get(arguments);
  31. if (id === null) return 0;
  32. if (!cache[id]) return 0;
  33. return cache[id];
  34. }),
  35. });
  36. };