Collection
Collection<K, V> extends JavaScript’s built-in Map with higher-order functional methods for querying and transforming data. All resource caches in Lunibee use Collection.
Import
Section titled “Import”import { Collection } from "lunibee";// or from the sub-package:import { Collection } from "@lunibee/collection";import { Collection } from "lunibee";// or from the sub-package:import { Collection } from "@lunibee/collection";Constructor
Section titled “Constructor”const col = new Collection<string, User>();// From entries:const col = new Collection([["id1", user1], ["id2", user2]]);const col = new Collection();// From entries:const col = new Collection([["id1", user1], ["id2", user2]]);Inherited Map Methods
Section titled “Inherited Map Methods”All standard Map methods are available: get, set, delete, has, clear, size, forEach, keys, values, entries.
Additional Methods
Section titled “Additional Methods”find(predicate)
Section titled “find(predicate)”Returns the first value matching the predicate, or undefined.
const admin = client.users.cache.find(u => u.username === "admin");const admin = client.users.cache.find(u => u.username === "admin");findKey(predicate)
Section titled “findKey(predicate)”Returns the first key matching the predicate, or undefined.
const adminId = client.users.cache.findKey(u => u.username === "admin");const adminId = client.users.cache.findKey(u => u.username === "admin");findLast(predicate) and findLastKey(predicate)
Section titled “findLast(predicate) and findLastKey(predicate)”Like find() and findKey(), but search from the last entry (insertion order) backwards.
const newestBot = client.users.cache.findLast(u => u.bot);const newestBotId = client.users.cache.findLastKey(u => u.bot);filter(predicate)
Section titled “filter(predicate)”Returns a new Collection containing only entries where the predicate returns true.
const bots = client.users.cache.filter(u => u.bot);const bots = client.users.cache.filter(u => u.bot);map(fn)
Section titled “map(fn)”Returns an array of the results of calling fn on every value.
const usernames = client.users.cache.map(u => u.username);// → ["alice", "bob", "lunibee_bot", ...]const usernames = client.users.cache.map(u => u.username);// → ["alice", "bob", "lunibee_bot", ...]flatMap(fn)
Section titled “flatMap(fn)”Returns a flat array from a function that returns arrays.
reduce(fn, initialValue)
Section titled “reduce(fn, initialValue)”Reduces the collection to a single value.
const totalBoosters = client.guilds.cache.reduce( (acc, guild) => acc + guild.premiumSubscriptionCount, 0,);const totalBoosters = client.guilds.cache.reduce( (acc, guild) => acc + guild.premiumSubscriptionCount, 0,);some(predicate)
Section titled “some(predicate)”Returns true if any entry matches the predicate.
const hasBot = client.users.cache.some(u => u.bot);const hasBot = client.users.cache.some(u => u.bot);every(predicate)
Section titled “every(predicate)”Returns true if all entries match the predicate.
first()
Section titled “first()”Returns the first value (insertion order), or undefined when empty.
const firstUser = client.users.cache.first();const firstUser = client.users.cache.first();last()
Section titled “last()”Returns the last value, or undefined when empty.
firstKey() / lastKey()
Section titled “firstKey() / lastKey()”Returns the first or last key, or undefined when empty.
at(index)
Section titled “at(index)”Returns the value at a numeric index (supports negative for reverse).
const lastUser = client.users.cache.at(-1);const lastUser = client.users.cache.at(-1);keyAt(index)
Section titled “keyAt(index)”Returns the key at a numeric index.
random(amount?)
Section titled “random(amount?)”Returns one random value (or undefined when empty). With amount, returns that many different values as an array; asking for more than the size returns all of them, shuffled, and 0 returns []. Throws a RangeError for a negative or fractional amount. Uses Math.random(), so do not use it for tokens or secrets.
const members = client.guilds.members(guildId).cache;const winner = members.random();const winners = members.random(3);randomKey(amount?)
Section titled “randomKey(amount?)”Same as random(), for keys.
sweep(predicate)
Section titled “sweep(predicate)”Removes all entries where the predicate returns true. Returns the number removed.
const removed = collection.sweep(u => u.bot);const removed = collection.sweep(u => u.bot);partition(predicate)
Section titled “partition(predicate)”Splits the collection into two: [matching, notMatching].
const [bots, humans] = client.users.cache.partition(u => u.bot);const [bots, humans] = client.users.cache.partition(u => u.bot);sorted(compareFn?)
Section titled “sorted(compareFn?)”Returns a new Collection sorted by the comparator.
const byName = client.guilds.cache.sorted((a, b) => a.name.localeCompare(b.name));const byName = client.guilds.cache.sorted((a, b) => a.name.localeCompare(b.name));union(other)
Section titled “union(other)”Returns a new Collection with the entries of both collections (other wins on key clashes).
intersection(other)
Section titled “intersection(other)”Returns entries whose keys are in both collections.
difference(other)
Section titled “difference(other)”Returns entries that are in this collection but not in other.
hasAll(...keys) / hasAny(...keys)
Section titled “hasAll(...keys) / hasAny(...keys)”Whether every / at least one of the keys is present.
clone()
Section titled “clone()”Returns a shallow copy.
tap(fn)
Section titled “tap(fn)”Calls fn(collection) and returns the collection unchanged, for side effects in a chain.
toJSON()
Section titled “toJSON()”Returns the entries as [key, value] pairs.
Example
Section titled “Example”List community guilds
const onlineMembers = client.guilds.cache .filter(g => g.isCommunity) .map(g => g.name);
console.log("Community guilds:", onlineMembers.join(", "));const onlineMembers = client.guilds.cache .filter(g => g.isCommunity) .map(g => g.name);
console.log("Community guilds:", onlineMembers.join(", "));Get the 5 newest user accounts
const newest = client.users.cache .sorted((a, b) => b.createdAt.getTime() - a.createdAt.getTime()) .array() .slice(0, 5);const newest = client.users.cache .sorted((a, b) => b.createdAt.getTime() - a.createdAt.getTime()) .array() .slice(0, 5);Combining and transforming
Section titled “Combining and transforming”None of these change the collection they are called on; each returns a new one (of the same class, see below) unless noted. other may be a Collection, any Map, or a ReadonlyCollection.
| Method | Returns |
|---|---|
concat(...collections) |
This collection’s entries, then each collection’s; a later one wins a shared key. |
symmetricDifference(other) |
The entries whose key is in only one of the two. |
merge(other, whenInSelf, whenInOther, whenInBoth) |
A collection of the entries the callbacks keep. Each callback returns { keep: true, value } or { keep: false }. |
mapValues(fn) |
The same keys with each value passed through fn(value, key, collection). |
toReversed() |
The entries in reverse order. |
toSorted(comparator?) |
The entries sorted, stable; same as sorted(). |
reduceRight(fn, initial) |
Folds from the last entry to the first, like reduce() from the first. |
equals(other) |
true when both have the same keys and === equal values. Does not touch either side’s TTL, recency or stats. |
Collection.groupBy(items, keySelector) |
A collection from each key to the array of items with that key. |
Collection.combineEntries(entries, combine) |
A collection from [key, value] pairs; combine(first, second, key) merges pairs that share a key. |
const byBot = Collection.groupBy(users.values(), u => (u.bot ? "bots" : "people"));const names = users.mapValues(u => u.username);const changes = before.merge( after, () => ({ keep: true, value: "removed" }), () => ({ keep: true, value: "added" }), (a, b) => (a === b ? { keep: false } : { keep: true, value: "changed" }),);ReadonlyCollection<K, V> is a Collection without set, delete, clear, get, ensure, sweep and the other methods that change it. Accept it in functions that only read.
There is no in-place sort() or reverse(): reordering a collection that tracks recency and TTL in place would break its bookkeeping. Use toSorted() and toReversed().
Subclassing
Section titled “Subclassing”filter(), clone(), sorted(), partition(), union(), intersection() and difference() return an instance of the same class (Symbol.species), built with no constructor arguments and without any ttl or maxSize. Override static get [Symbol.species]() to return Collection (or another class) instead.
import { Collection, type User } from "lunibee";
class Users extends Collection<string, User> {}const bots = new Users().filter(u => u.bot); // UsersTTL, LRU and Persistent Entries (0.2.0)
Section titled “TTL, LRU and Persistent Entries (0.2.0)”Without options a Collection behaves exactly like a Map. Pass options to
bound it:
const cache = new Collection<string, number>(null, { ttl: 60_000, // default sliding TTL for set() jitter: 0.2, // each TTL is 80-100% of ttl, so entries set together expire staggered maxSize: 1_000, // LRU cap for set() entries slide: true, // false: a read promotes but does not extend the TTL onEvict: (key, value, reason) => {}, // reason: "expired" | "evicted"});| Method | Description |
|---|---|
set(key, value, ttl?) |
Stores a TTL/LRU entry; ttl overrides the default for this entry. |
setWithoutTTL(key, value) |
Stores an entry that never expires and is never evicted by maxSize. Managers store Discord resources this way. |
get(key) |
Reads a value; restarts a TTL entry’s window and marks it recently used. |
peek(key) |
Reads without restarting the TTL or promoting. |
ensure(key, factory, ttl?) |
Returns the stored value, or stores and returns what factory(key, collection) makes. Reading counts as get(); creating uses set(). If factory throws, nothing is stored. |
ttlRemaining(key) |
Milliseconds until the entry expires, or undefined if it never does. |
purge() |
Removes expired entries now; returns how many. |
stats |
{ hits, misses, expired, evicted } counters. |
A later set() turns a setWithoutTTL() entry back into a TTL entry.
Expired entries are removed by a single unref’d timer and are never visible to
reads or iteration.
Sharing a collection between processes: RedisCollection
Section titled “Sharing a collection between processes: RedisCollection”A Collection lives in one process. RedisCollection keeps its entries in Redis, so every process that opens it with the same name (and prefix) shares them, with the same retention policy: a sliding TTL, maxSize evicting the least recently used across every process, and onEvict.
import { RedisCollection } from "lunibee";
const sessions = new RedisCollection<{ step: number }>({ client: new Bun.RedisClient(process.env.REDIS_URL!), // ioredis: { send: (c, a) => redis.call(c, ...a) } name: "sessions", // letters, digits, _ . : - (up to 100) prefix: "mybot:", // default "lunibee:collection:"; keys live under <prefix>v1:{name}: ttl: 15 * 60_000, // default TTL for set(), sliding unless slide: false maxSize: 10_000, // LRU across every process onEvict: (key, value, reason) => {}, // for removals this instance's operations make});
await sessions.set(userId, { step: 1 });const session = await sessions.get(userId); // from any processconst fresh = await sessions.ensure(userId, () => ({ step: 0 }));| Method | Description |
|---|---|
get(key) |
The value, or undefined. Marks it recently used; with slide, restarts its TTL. |
peek(key), has(key) |
Read without marking or restarting. |
set(key, value, ttl?) |
Stores with the default TTL, or ttl ms (0: never expires). |
setWithoutTTL(key, value) |
Stores with no expiry. Unlike Collection, it still counts towards maxSize. |
ensure(key, factory, ttl?) |
Returns the stored value, or stores what factory gives. When processes race, one value wins and every caller gets it. |
delete(key), clear() |
Remove one entry (true if it was there) / all (returns how many). |
size(), keys(), values(), entries() |
Live entries, least recently used first. |
ttlRemaining(key) |
Milliseconds left, or undefined when it never expires or is absent. |
stats |
{ hits, misses, expired, evicted } seen by this instance. |
Every method is async. Each operation is one atomic Lua script that reads the time from Redis, so processes never see a half-applied write and skewed clocks do not change expiry. Keys are strings (numbers are converted). Values are JSON by default; pass serializer: { serialize, deserialize } for values JSON cannot carry, such as bigint or Map. All keys of one collection share a Redis Cluster hash slot ({name}). onEvict reports the removals this instance’s own calls perform; another process’s calls are reported to that process.