A basic key value store with bounded capacity for simple caching.
npm install @alexsasharegan/simple-cache





A basic key value store with bounded capacity for simple caching.
``sh`
npm install @alexsasharegan/simple-cache
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 an Option (maybe type)Cache.remove
- : remove a value by keyCache.clear
- : empty the cache
Creating a cache looks like this in plain JavaScript:
`jstoString
// 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
// behavior.`
let userCache = SimpleCache(10, { key: "ID", value: "User" })
userCache.toString()
// SimpleCache
If you're using TypeScript, you need to create a cache by declaring the key and
value types as generic parameters:
`ts
interface User {
id: number
name: string
}
let userCache = SimpleCache
userCache.toString()
// SimpleCache
`
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 fromCache.get, visit the
safe-types repository.
`js
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.
`ts
// Sets a capacity of 10 users and a max lifetime of 5 seconds
let userCache = EphemeralCache
key: "ID",
value: "User",
})
userCache.write(1, { name: "Temp", id: 1 })
setTimeout(() => {
userCache.read(1)
// undefined
}, 5001)
userCache.read(1)
// { name: "Temp", id: 1 }
``