Created
June 10, 2019 09:03
-
-
Save kindlyfire/9304d06ad54eb59d17788f3f71027755 to your computer and use it in GitHub Desktop.
A JavaScript FixedCache implementation
This file contains 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
/** | |
* Creates a fixed-length cache | |
* | |
* @module FixedCache | |
*/ | |
export default class FixedCache { | |
/** | |
* @param {Number} size Integer for the cache size | |
*/ | |
constructor(size) { | |
if (size < 1) { | |
throw new Error('Size cannot be smaller than one') | |
} | |
this.store = new Array(size).fill(null) | |
this.ptr = 0 | |
this.size = size | |
} | |
/** | |
* Set a cache item | |
* | |
* @param {string} key Resource identifier | |
* @param {Object} value The value | |
*/ | |
set(key, value) { | |
this.store[this.ptr] = { | |
key, | |
value | |
} | |
this.ptr = (this.ptr + 1) % this.size | |
} | |
/** | |
* Get a value from the cache, or null | |
* | |
* @param {string} key The key of the value to search for | |
* @returns {(Object|undefined)} The found (or not found) object | |
*/ | |
get(key) { | |
return this.store.find((item) => item && item.key === key) | |
} | |
/** | |
* Check if a key is currently in the cache | |
* | |
* @param {string} key The key of the value to search for | |
* @returns {boolean} Wether the key was found in the cache | |
*/ | |
has(key) { | |
return this.get(key) !== undefined | |
} | |
/** | |
* | |
* @param {string} key The key of the value to search for | |
* @returns {Object|undefined} The popped value | |
*/ | |
pop(key) { | |
const index = this.store.findIndex((item) => item && item.key === key) | |
if (index === -1) { | |
return | |
} | |
const item = this.store[index] | |
this.store[index] = null | |
return item | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment