@alexsasharegan/simple-cache
v3.3.3
Published
A basic key value store with bounded capacity for simple caching.
Downloads
1,332
Readme
simple-cache
A basic key value store with bounded capacity for simple caching.
Install
npm install @alexsasharegan/simple-cache
Documentation
Visit the API Documentation here.
Cache is an interface for caching key/value pairs of types K
/V
. It's primary
functionality includes:
Cache.write
: write a value at a keyCache.read
: read a value from a keyCache.get
: read a value as anOption<V>
(maybe type)Cache.remove
: remove a value by keyCache.clear
: empty the cache
Usage
Creating a cache looks like this in plain JavaScript:
// Creates a cache with a capacity of 10 items. The second parameter is the
// "type label". It serves as a convenience option for more meaningful
// `toString` behavior.
let userCache = SimpleCache(10, { key: "ID", value: "User" })
userCache.toString()
// SimpleCache<ID, User> { size: 0, capacity: 10 }
If you're using TypeScript, you need to create a cache by declaring the key and value types as generic parameters:
interface User {
id: number
name: string
}
let userCache = SimpleCache<number, User>(10, { key: "ID", value: "User" })
userCache.toString()
// SimpleCache<ID, User> { size: 0, capacity: 10 }
Here are some examples of the five main interaction methods shown in REPL style.
If you're curious to learn more about the Option
type returned from
Cache.get
, visit the
safe-types repository.
let userA = { name: "User A", id: 1 }
let userB = { name: "User B", id: 2 }
userCache.write(userA.id, userA)
userCache.write(userB.id, userB)
userCache.size()
// 2
userCache.read(1)
// { name: "User A", id: 1 }
userCache.read(2)
// { name: "User B", id: 2 }
userCache.get(2)
// Some<{ name: "User B", id: 2 }>
userCache.read(3)
// undefined
userCache.get(3)
// None
userCache.remove(1)
userCache.size()
// 1
userCache.read(1)
// undefined
userCache.clear()
userCache.size()
// 0
There is an Ephemeral Cache available. It caches items for a duration that's given in milliseconds.
// Sets a capacity of 10 users and a max lifetime of 5 seconds
let userCache = EphemeralCache<number, User>(10, 5000, {
key: "ID",
value: "User",
})
userCache.write(1, { name: "Temp", id: 1 })
setTimeout(() => {
userCache.read(1)
// undefined
}, 5001)
userCache.read(1)
// { name: "Temp", id: 1 }