roblox-cache
v1.0.3-beta.1
Published
A small in-memory cache for roblox-ts
Downloads
108
Maintainers
Readme
RobloxCache
A small in-memory cache for roblox-ts with:
- LRU eviction (Least Recently Used): when the cache is full, the least recently accessed item is removed
- optional TTL (Time To Live): items can expire automatically after
nseconds
Use it to avoid repeating expensive work (computations, HTTP calls, DataStore reads, etc.).
Install
npm i roblox-cacheConfigs
interface RobloxCacheConfig {
maxSize?: number; // default 1000
debug?: boolean; // default false
}maxSize: maximum number of entries before LRU eviction kicks indebug: whentrue, logs cache actions usingwarn()
Configs usage
new RobloxCache({
maxSize?: number;
debug?: boolean;
})Basic usage
import RobloxCache from "roblox-cache";
const cache = new RobloxCache({ maxSize: 500, debug: false });
cache.set("score:blue", 1);
cache.set("score:red", 2);
print(`Blue: ${cache.get("score:blue")} - Red: ${cache.get("score:red")}`); // Blue: 1 - Red: 2TTL (Time To Live)
TTL is in seconds. When a value is expired, get returns undefined (and has becomes false).
DashActivated.Connect((p: Player) => {
cache.set(`cooldown:Dash_${p.Name}`, true, 3); // expires after 3 seconds
print(cache.get(`cooldown:Dash_${p.Name}`)) // true
task.wait(3)
print(cache.get(`cooldown:Dash_${p.Name}`)) // undefined
})remember (cache async work)
remember runs an async function once and caches its result. If the value is already cached (and not expired),
it returns the cached value and does not run the function again.
type Profile = { level: number };
const profiles = new RobloxCache<Profile>({ maxSize: 200 });
const profile = await profiles.remember(
"profile:123",
async () => {
// ...
return { level: 7 };
},
60, // keep for 60 seconds
);API
new RobloxCache<T>(config?: { maxSize?: number; debug?: boolean })
set(key: string, value: T, ttl?: number): void
get(key: string): T | undefined
has(key: string): boolean
delete(key: string): boolean
clear(): void
size(): number
remember<R>(key: string, fn: () => Promise<R>, ttl?: number): Promise<R>
benchmark(iterations?: number): {
totalOps: number;
durationMs: number;
opsPerSecond: number;
hits: number;
misses: number;
}set
Stores a value under a key.
set(key: string, value: T, ttl?: number): void- If
keyalready exists, its value is replaced and it becomes “most recently used”. ttlis optional and measured in seconds. When provided and> 0, the entry expires afterttlseconds.
get
Retrieves a value by key.
get(key: string): T | undefined- Returns
undefinedif the key is missing or the entry is expired. - Updates recency (LRU): a successful
getmarks the entry as “most recently used”.
has
Checks whether a valid (non-expired) value exists for the key.
has(key: string): boolean- Returns
trueonly whenget(key)would return a value. - Note: this method calls
getinternally, so it also updates recency (LRU) when the key exists.
delete
Removes a key from the cache.
delete(key: string): boolean- Returns
trueif an entry was removed.
clear
Removes all entries.
clear(): voidsize
Returns the current number of stored entries.
size(): numberremember
Caches the result of an async function.
remember<R>(key: string, fn: () => Promise<R>, ttl?: number): Promise<R>- If
keyis cached (and not expired), returns the cached value immediately. - Otherwise runs
fn(), stores its result, then returns it. ttlis optional (seconds), same asset.
benchmark
Runs a simple hit/miss benchmark against the cache (useful for quick sanity/perf checks).
benchmark(iterations?: number): {
totalOps: number;
durationMs: number;
opsPerSecond: number;
hits: number;
misses: number;
}iterationsdefaults to100000.- Returns totals plus hit/miss counts and approximate throughput.
