transitory
Version:
In-memory cache with high hit rates via LFU eviction. Supports time-based expiration, automatic loading and metrics.
75 lines • 2.84 kB
JavaScript
;
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.memoryEstimator = void 0;
var CacheNode_1 = require("../cache/CacheNode");
var OBJ_OVERHEAD = 4;
/**
* Estimate the memory usage of the given object.
*
* @param value -
* value to estimates
* @returns
* estimated memory usage in bytes
*/
function memoryEstimator(value) {
var e_1, _a;
switch (typeof value) {
case 'string':
return OBJ_OVERHEAD + (value.length * 2);
case 'boolean':
return 4;
case 'number':
return 8;
case 'object':
{
if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) {
return OBJ_OVERHEAD + value.length;
}
else if (Array.isArray(value)) {
var arraySize = OBJ_OVERHEAD;
try {
for (var value_1 = __values(value), value_1_1 = value_1.next(); !value_1_1.done; value_1_1 = value_1.next()) {
var v = value_1_1.value;
arraySize += memoryEstimator(v);
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (value_1_1 && !value_1_1.done && (_a = value_1.return)) _a.call(value_1);
}
finally { if (e_1) throw e_1.error; }
}
return arraySize;
}
else if (value instanceof CacheNode_1.CacheNode) {
// Treat cache nodes as having a key and value field
return OBJ_OVERHEAD
+ OBJ_OVERHEAD + memoryEstimator(value.key)
+ OBJ_OVERHEAD + memoryEstimator(value.value);
}
var size_1 = OBJ_OVERHEAD;
Object.keys(value).forEach(function (key) {
size_1 += OBJ_OVERHEAD;
size_1 += memoryEstimator(key);
size_1 += memoryEstimator(value[key]);
});
return size_1;
}
default:
return 0;
}
}
exports.memoryEstimator = memoryEstimator;
//# sourceMappingURL=memoryEstimator.js.map