CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-discordjs--collection

Utility data structure used in discord.js that extends JavaScript's native Map class with additional methods for enhanced functionality

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

collection-operations.mddocs/

Collection Operations

Set-like operations for combining, comparing, and manipulating multiple collections. These methods enable powerful collection algebra and data management patterns.

Capabilities

Collection Combining

Methods for merging and concatenating collections.

/**
 * Creates an identical shallow copy of this collection
 * @returns New collection with same entries
 */
clone(): Collection<Key, Value>;

/**
 * Combines this collection with others into a new collection. None of the source collections are modified
 * @param collections - Collections to merge
 * @returns New collection containing all entries
 */
concat(...collections: ReadonlyCollection<Key, Value>[]): Collection<Key, Value>;

Usage Examples:

import { Collection } from "@discordjs/collection";

const users1 = new Collection([
  ["alice", { name: "Alice", team: "red" }],
  ["bob", { name: "Bob", team: "blue" }]
]);

const users2 = new Collection([
  ["charlie", { name: "Charlie", team: "red" }],
  ["diana", { name: "Diana", team: "blue" }]
]);

// Clone a collection
const usersCopy = users1.clone();
// usersCopy is independent of users1

// Combine collections
const allUsers = users1.concat(users2);
// Result: Collection with all 4 users
// Original collections remain unchanged

Collection Comparison

Compare collections for equality.

/**
 * Checks if this collection shares identical items with another
 * This is different to checking for equality using equal-signs, because
 * the collections may be different objects, but contain the same data
 * @param collection - Collection to compare with
 * @returns Whether the collections have identical contents
 */
equals(collection: ReadonlyCollection<Key, Value>): boolean;

Usage Example:

const coll1 = new Collection([["a", 1], ["b", 2]]);
const coll2 = new Collection([["a", 1], ["b", 2]]);
const coll3 = new Collection([["a", 1], ["b", 3]]);

console.log(coll1.equals(coll2)); // true (same contents)
console.log(coll1.equals(coll3)); // false (different values)
console.log(coll1 === coll2); // false (different objects)

Set Operations

Mathematical set operations for working with collection intersections, unions, and differences.

/**
 * The intersection method returns a new collection containing the items where the key is present in both collections
 * @param other - The other Collection to filter against
 * @returns New collection with keys present in both collections
 */
intersection(other: ReadonlyCollection<Key, any>): Collection<Key, Value>;

/**
 * Returns a new collection containing the items where the key is present in either of the collections
 * If the collections have any items with the same key, the value from the first collection will be used
 * @param other - The other Collection to filter against
 * @returns New collection with keys present in either collection
 */
union<OtherValue>(other: ReadonlyCollection<Key, OtherValue>): Collection<Key, OtherValue | Value>;

/**
 * Returns a new collection containing the items where the key is present in this collection but not the other
 * @param other - The other Collection to filter against
 * @returns New collection with keys only in this collection
 */
difference(other: ReadonlyCollection<Key, any>): Collection<Key, Value>;

/**
 * Returns a new collection containing only the items where the keys are present in either collection, but not both
 * @param other - The other Collection to filter against
 * @returns New collection with keys in either collection but not both
 */
symmetricDifference<OtherValue>(other: ReadonlyCollection<Key, OtherValue>): Collection<Key, OtherValue | Value>;

Usage Examples:

const redTeam = new Collection([
  ["alice", { name: "Alice", score: 95 }],
  ["bob", { name: "Bob", score: 87 }],
  ["charlie", { name: "Charlie", score: 92 }]
]);

const highScorers = new Collection([
  ["alice", { name: "Alice", score: 95 }],
  ["charlie", { name: "Charlie", score: 92 }],
  ["diana", { name: "Diana", score: 98 }]
]);

// Intersection - members who are both on red team AND high scorers
const redHighScorers = redTeam.intersection(highScorers);
// Result: Collection with alice and charlie

// Union - all members from either group
const allMembers = redTeam.union(highScorers);
// Result: Collection with alice, bob, charlie, diana
// Note: alice and charlie keep their redTeam values

// Difference - red team members who are NOT high scorers
const redOnly = redTeam.difference(highScorers);
// Result: Collection with bob only

// Symmetric difference - members in either group but not both
const exclusive = redTeam.symmetricDifference(highScorers);
// Result: Collection with bob and diana

Advanced Merging

Sophisticated merging with custom conflict resolution.

/**
 * Merges two Collections together into a new Collection
 * @param other - The other Collection to merge with
 * @param whenInSelf - Function getting the result if the entry only exists in this Collection
 * @param whenInOther - Function getting the result if the entry only exists in the other Collection
 * @param whenInBoth - Function getting the result if the entry exists in both Collections
 * @returns New collection with merged results
 */
merge<OtherValue, ResultValue>(
  other: ReadonlyCollection<Key, OtherValue>,
  whenInSelf: (value: Value, key: Key) => Keep<ResultValue>,
  whenInOther: (valueOther: OtherValue, key: Key) => Keep<ResultValue>,
  whenInBoth: (value: Value, valueOther: OtherValue, key: Key) => Keep<ResultValue>
): Collection<Key, ResultValue>;

type Keep<Value> = { keep: false } | { keep: true; value: Value };

Usage Examples:

const inventory1 = new Collection([
  ["sword", { count: 5, quality: "good" }],
  ["shield", { count: 2, quality: "excellent" }],
  ["potion", { count: 10, quality: "common" }]
]);

const inventory2 = new Collection([
  ["sword", { count: 3, quality: "excellent" }],
  ["bow", { count: 1, quality: "rare" }],
  ["potion", { count: 5, quality: "good" }]
]);

// Merge inventories - sum counts, keep better quality
const mergedInventory = inventory1.merge(
  inventory2,
  // Item only in first inventory
  (item) => ({ keep: true, value: item }),
  // Item only in second inventory  
  (item) => ({ keep: true, value: item }),
  // Item in both inventories
  (item1, item2) => ({
    keep: true,
    value: {
      count: item1.count + item2.count,
      quality: item1.quality === "excellent" || item2.quality === "excellent" 
        ? "excellent" 
        : item1.quality === "rare" || item2.quality === "rare"
        ? "rare"
        : item1.quality === "good" || item2.quality === "good"
        ? "good"
        : "common"
    }
  })
);

// Advanced example - filter during merge
const importantItemsOnly = inventory1.merge(
  inventory2,
  (item) => item.count > 5 ? { keep: true, value: item } : { keep: false },
  (item) => item.quality === "rare" ? { keep: true, value: item } : { keep: false },
  (item1, item2) => ({
    keep: item1.count + item2.count > 10,
    value: { count: item1.count + item2.count, quality: item1.quality }
  })
);

Sorting and Reversing

Methods for reordering collection entries.

/**
 * Identical to Array.reverse() but returns a Collection instead of an Array
 * Reverses the collection in place
 * @returns The collection itself for chaining
 */
reverse(): this;

/**
 * The sort method sorts the items of a collection in place and returns it
 * The sort is not necessarily stable in Node 10 or older
 * The default sort order is according to string Unicode code points
 * @param compareFunction - Specifies a function that defines the sort order
 * @returns The collection itself for chaining
 */
sort(compareFunction?: Comparator<Key, Value>): this;

/**
 * Identical to Array.toReversed() but returns a Collection instead of an Array
 * Returns a new reversed collection without modifying the original
 * @returns New reversed collection
 */
toReversed(): Collection<Key, Value>;

/**
 * The sorted method sorts the items of a collection and returns it
 * Returns a new sorted collection without modifying the original
 * @param compareFunction - Specifies a function that defines the sort order
 * @returns New sorted collection
 */
toSorted(compareFunction?: Comparator<Key, Value>): Collection<Key, Value>;

type Comparator<Key, Value> = (firstValue: Value, secondValue: Value, firstKey: Key, secondKey: Key) => number;

Usage Examples:

const players = new Collection([
  ["alice", { name: "Alice", score: 95, level: 10 }],
  ["bob", { name: "Bob", score: 87, level: 8 }],
  ["charlie", { name: "Charlie", score: 92, level: 12 }]
]);

// Sort by score (descending) - modifies original
players.sort((a, b) => b.score - a.score);
// Order: alice (95), charlie (92), bob (87)

// Sort by level without modifying original
const sortedByLevel = players.toSorted((a, b) => b.level - a.level);
// sortedByLevel: charlie (12), alice (10), bob (8)
// players remains in score order

// Reverse the collection
const reversed = players.toReversed();
// If players was [alice, charlie, bob], reversed is [bob, charlie, alice]

Serialization

Convert collections to JSON-serializable formats.

/**
 * Converts the collection to a JSON-serializable array of [key, value] pairs
 * @returns Array of [key, value] tuples
 */
toJSON(): [Key, Value][];

Usage Example:

const settings = new Collection([
  ["theme", "dark"],
  ["language", "en"],
  ["notifications", true]
]);

const json = JSON.stringify(settings);
// Result: '[["theme","dark"],["language","en"],["notifications",true]]'

// Can be reconstructed
const reconstructed = new Collection(JSON.parse(json));
// reconstructed equals the original settings collection

Static Methods

Utility methods available on the Collection class itself.

/**
 * Creates a Collection from a list of entries
 * @param entries - The list of entries
 * @param combine - Function to combine an existing entry with a new one
 * @returns New collection with combined entries
 */
static combineEntries<Key, Value>(
  entries: Iterable<[Key, Value]>,
  combine: (firstValue: Value, secondValue: Value, key: Key) => Value
): Collection<Key, Value>;

Usage Example:

// Combine duplicate entries by summing values
const combined = Collection.combineEntries(
  [["a", 1], ["b", 2], ["a", 3], ["c", 4], ["b", 1]],
  (existing, newValue) => existing + newValue
);
// Result: Collection { "a" => 4, "b" => 3, "c" => 4 }

// Combine by keeping latest value
const latest = Collection.combineEntries(
  [["user1", { name: "Alice", version: 1 }], ["user1", { name: "Alice Smith", version: 2 }]],
  (existing, newValue) => newValue.version > existing.version ? newValue : existing
);
// Result: Collection with user1 having version 2 data

Install with Tessl CLI

npx tessl i tessl/npm-discordjs--collection

docs

array-like-methods.md

collection-operations.md

core-methods.md

index.md

tile.json