Debian Codegraph @

memoizee/ext/ref-counter.js

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