expiry-set
Version:
A Set implementation with expirable keys
71 lines (70 loc) • 1.82 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class ExpirySet {
constructor(maxAge, values) {
this.maxAge = maxAge;
this[Symbol.toStringTag] = 'Set';
this.data = new Map();
if (values) { // tslint:disable-line:early-exit
for (const key of values) {
this.add(key);
}
}
}
get size() {
return [...this.entries()].length;
}
add(key) {
this.data.set(key, Date.now());
return this;
}
clear() {
this.data.clear();
}
delete(key) {
const hasKey = this.has(key);
if (hasKey) {
this.data.delete(key);
}
return hasKey;
}
has(key) {
const timestamp = this.data.get(key);
return Boolean(timestamp && !this.isExpired([key, timestamp]));
}
values() {
return this.createIterator(item => item[0]);
}
keys() {
return this.values();
}
entries() {
return this.createIterator(item => [item[0], item[0]]);
}
forEach(callbackfn, thisArg) {
for (const [key, value] of this.entries()) {
callbackfn.apply(thisArg, [value, key, this]);
}
}
[Symbol.iterator]() {
return this.values();
}
isExpired([key, timestamp]) {
const isExpired = Date.now() - timestamp > this.maxAge;
if (isExpired) {
this.data.delete(key);
}
return isExpired;
}
*createIterator(projection) {
for (const item of this.data.entries()) {
if (!this.isExpired(item)) {
yield projection(item);
}
}
}
}
exports.default = ExpirySet;
// Add support for CJS
module.exports = ExpirySet;
module.exports.default = ExpirySet;