@knowmax/genericlist-core
Version:
Knowmax Generic list with basic CRUD support without any user interface implementation.
45 lines (44 loc) • 1.3 kB
JavaScript
export class GenericListCache {
constructor(maxSize) {
Object.defineProperty(this, "list", {
enumerable: true,
configurable: true,
writable: true,
value: []
});
Object.defineProperty(this, "maxSize", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
this.maxSize = maxSize;
}
get(key) {
const list = this.list.find((item) => item.key === key)?.value;
return list ? list : undefined;
}
getOrCreate(key, creator) {
return (this.list.find((item) => item.key === key)?.value ?? this.set(key, creator));
}
set(key, creator) {
const list = creator();
const index = this.list.findIndex((item) => item.key === key);
if (index !== -1) {
this.list[index].value = list;
}
else {
if (this.list.length === this.maxSize) {
this.list.shift();
}
this.list.push({ key: key, value: list });
}
return list;
}
remove(key) {
const index = this.list.findIndex((item) => item.key === key);
if (index !== -1) {
this.list.splice(index, 1);
}
}
}