Skip to content

Instantly share code, notes, and snippets.

@hawaijar
Created May 13, 2021 05:43
Show Gist options
  • Save hawaijar/44bd71de63abcf51c3a0889eeac18cce to your computer and use it in GitHub Desktop.
Save hawaijar/44bd71de63abcf51c3a0889eeac18cce to your computer and use it in GitHub Desktop.
Simple LRU cache using only Array
const LRUCache = function (capacity) {
this.cache = [];
this.capacity = capacity;
this.count = 0;
};
LRUCache.prototype.get = function (key) {
const obj = this.cache.find((item) => item.key === key);
if (obj) {
this.cache = this.cache.filter((item) => item.key !== key);
this.cache.push(obj);
return obj.value;
} else {
return -1;
}
};
LRUCache.prototype.put = function (key, value) {
// check if the key is already there in the cache
const obj = this.cache.find((item) => item.key === key);
if (obj) {
this.cache = this.cache.filter((item) => item.key !== key);
this.cache.push({
key,
value,
});
} else {
if (this.count < this.capacity) {
this.count += 1;
this.cache.push({
key,
value,
});
} else {
// this.cache = this.cache.sort((a, b) => a["time"] - b["time"]);
this.cache.shift();
this.cache.push({
key,
value,
});
}
}
};
let lRUCache = new LRUCache(2);
lRUCache.put(1, 1);
lRUCache.put(2, 2);
console.log(lRUCache.get(1)); // 1
lRUCache.put(3, 3);
console.log(lRUCache.get(2)); // -1
lRUCache.put(4, 4);
console.log(lRUCache.get(1)); // -1
console.log(lRUCache.get(3)); // 3
console.log(lRUCache.get(4)); // 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment