Last active
October 14, 2019 15:40
-
-
Save uhop/f8f63ffd7634d790cc2b8ff6d16a90e9 to your computer and use it in GitHub Desktop.
Simple cache implementation.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It uses
List
from https://gist.github.com/uhop/f17409a95a14f10e1cbd5a584ca9d245