Skip to content

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 { Collection } from "lunibee";
// or from the sub-package:
import { Collection } from "@lunibee/collection";
const col = new Collection<string, User>();
// From entries:
const col = new Collection([["id1", user1], ["id2", user2]]);

All standard Map methods are available: get, set, delete, has, clear, size, forEach, keys, values, entries.

Returns the first value matching the predicate, or undefined.

const admin = client.users.cache.find(u => u.username === "admin");

Returns the first key matching the predicate, or undefined.

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);

Returns a new Collection containing only entries where the predicate returns true.

const bots = client.users.cache.filter(u => u.bot);

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", ...]

Returns a flat array from a function that returns arrays.

Reduces the collection to a single value.

const totalBoosters = client.guilds.cache.reduce(
(acc, guild) => acc + guild.premiumSubscriptionCount,
0,
);

Returns true if any entry matches the predicate.

const hasBot = client.users.cache.some(u => u.bot);

Returns true if all entries match the predicate.

Returns the first value (insertion order), or undefined when empty.

const firstUser = client.users.cache.first();

Returns the last value, or undefined when empty.

Returns the first or last key, or undefined when empty.

Returns the value at a numeric index (supports negative for reverse).

const lastUser = client.users.cache.at(-1);

Returns the key at a numeric index.

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);

Same as random(), for keys.

Removes all entries where the predicate returns true. Returns the number removed.

const removed = collection.sweep(u => u.bot);

Splits the collection into two: [matching, notMatching].

const [bots, humans] = client.users.cache.partition(u => u.bot);

Returns a new Collection sorted by the comparator.

const byName = client.guilds.cache.sorted((a, b) => a.name.localeCompare(b.name));

Returns a new Collection with the entries of both collections (other wins on key clashes).

Returns entries whose keys are in both collections.

Returns entries that are in this collection but not in other.

Whether every / at least one of the keys is present.

Returns a shallow copy.

Calls fn(collection) and returns the collection unchanged, for side effects in a chain.

Returns the entries as [key, value] pairs.

List community guilds

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);

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().

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); // Users

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 process
const 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.