Skip to content

Instantly share code, notes, and snippets.

@uhop
Last active October 14, 2019 15:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uhop/f8f63ffd7634d790cc2b8ff6d16a90e9 to your computer and use it in GitHub Desktop.
Save uhop/f8f63ffd7634d790cc2b8ff6d16a90e9 to your computer and use it in GitHub Desktop.
Simple cache implementation.
'use strict';
const List = require('./List');
class Cache {
constructor(capacity = 10) {
this.capacity = capacity;
this.size = 0;
this.list = new List();
this.dict = {};
}
find(key) {
const node = this.dict[key];
if (typeof node == 'object') {
return node.value.value;
}
}
remove(key) {
const node = this.dict[key];
if (typeof node == 'object') {
delete this.dict[key];
node.pop();
--this.size;
}
return this;
}
register(key, value) {
const node = this.dict[key];
if (typeof node == 'object') {
this.list.moveToFront(node);
node.value = value;
} else {
if (this.size >= this.capacity) {
const node = this.list.back;
this.list.moveToFront(node);
delete this.dict[node.value.key];
this.dict[key] = node;
node.value = {key, value};
} else {
this.list.pushFront({key, value});
++this.size;
this.dict[key] = this.list.front;
}
}
return this;
}
clear() {
this.dict = {};
this.list.clear();
this.size = 0;
return this;
}
[Symbol.iterator]() {
return this.list[Symbol.iterator]();
}
getReverseIterable() {
return this.list.getReverseIterable();
}
}
module.exports = Cache;
@uhop
Copy link
Author

uhop commented Oct 11, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment