@discordjs/collection

  • Version 2.0.0
  • Published
  • 216 kB
  • No dependencies
  • Apache-2.0 license

Install

npm i @discordjs/collection
yarn add @discordjs/collection
pnpm add @discordjs/collection

Overview

Utility data structure used in discord.js

Index

Variables

variable version

const version: string;

Classes

class Collection

class Collection<Key, Value> extends Map<Key, Value> {}
  • A Map with additional utility methods. This is used throughout discord.js rather than Arrays for anything that has an ID, for significantly improved performance and ease-of-use.

method at

at: (index: number) => Value | undefined;
  • Identical to Array.at(). Returns the item at a given index, allowing for positive and negative integers. Negative integers count back from the last item in the collection.

    Parameter index

    The index of the element to obtain

method clone

clone: () => Collection<Key, Value>;
  • Creates an identical shallow copy of this collection.

    Example 1

    const newColl = someColl.clone();

method combineEntries

static combineEntries: <Key, Value>(
entries: Iterable<[Key, Value]>,
combine: (firstValue: Value, secondValue: Value, key: Key) => Value
) => Collection<Key, Value>;
  • Creates a Collection from a list of entries.

    Parameter entries

    The list of entries

    Parameter combine

    Function to combine an existing entry with a new one

    Example 1

    Collection.combineEntries([["a", 1], ["b", 2], ["a", 2]], (x, y) => x + y);
    // returns Collection { "a" => 3, "b" => 2 }

method concat

concat: (
...collections: ReadonlyCollection<Key, Value>[]
) => Collection<Key, Value>;
  • Combines this collection with others into a new collection. None of the source collections are modified.

    Parameter collections

    Collections to merge

    Example 1

    const newColl = someColl.concat(someOtherColl, anotherColl, ohBoyAColl);

method difference

difference: (other: ReadonlyCollection<Key, any>) => Collection<Key, Value>;
  • Returns a new collection containing the items where the key is present in this collection but not the other.

    Parameter other

    The other Collection to filter against

    Example 1

    const col1 = new Collection([['a', 1], ['b', 2]]);
    const col2 = new Collection([['a', 1], ['c', 3]]);
    console.log(col1.difference(col2));
    // => Collection { 'b' => 2 }
    console.log(col2.difference(col1));
    // => Collection { 'c' => 3 }

method each

each: {
(fn: (value: Value, key: Key, collection: this) => void): this;
<This>(
fn: (this: This, value: Value, key: Key, collection: this) => void,
thisArg: This
): this;
};
  • Identical to Map.forEach(), but returns the collection instead of undefined.

    Parameter fn

    Function to execute for each element

    Parameter thisArg

    Value to use as this when executing the function

    Example 1

    collection
    .each(user => console.log(user.username))
    .filter(user => user.bot)
    .each(user => console.log(user.username));

method ensure

ensure: (
key: Key,
defaultValueGenerator: (key: Key, collection: this) => Value
) => Value;
  • Obtains the value of the given key if it exists, otherwise sets and returns the value provided by the default value generator.

    Parameter key

    The key to get if it exists, or set otherwise

    Parameter defaultValueGenerator

    A function that generates the default value

    Example 1

    collection.ensure(guildId, () => defaultGuildConfig);

method equals

equals: (collection: ReadonlyCollection<Key, Value>) => boolean;
  • 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.

    Parameter collection

    Collection to compare with

    Returns

    Whether the collections have identical contents

method every

every: {
<NewKey extends Key>(
fn: (value: Value, key: Key, collection: this) => key is NewKey
): this is Collection<NewKey, Value>;
<NewValue extends Value>(
fn: (value: Value, key: Key, collection: this) => value is NewValue
): this is Collection<Key, NewValue>;
(fn: (value: Value, key: Key, collection: this) => unknown): boolean;
<This, NewKey extends Key>(
fn: (
this: This,
value: Value,
key: Key,
collection: this
) => key is NewKey,
thisArg: This
): this is Collection<NewKey, Value>;
<This, NewValue extends Value>(
fn: (
this: This,
value: Value,
key: Key,
collection: this
) => value is NewValue,
thisArg: This
): this is Collection<Key, NewValue>;
<This>(
fn: (this: This, value: Value, key: Key, collection: this) => unknown,
thisArg: This
): boolean;
};
  • Checks if all items passes a test. Identical in behavior to Array.every().

    Parameter fn

    Function used to test (should return a boolean)

    Parameter thisArg

    Value to use as this when executing the function

    Example 1

    collection.every(user => !user.bot);

method filter

filter: {
<NewKey extends Key>(
fn: (value: Value, key: Key, collection: this) => key is NewKey
): Collection<NewKey, Value>;
<NewValue extends Value>(
fn: (value: Value, key: Key, collection: this) => value is NewValue
): Collection<Key, NewValue>;
(fn: (value: Value, key: Key, collection: this) => unknown): Collection<
Key,
Value
>;
<This, NewKey extends Key>(
fn: (
this: This,
value: Value,
key: Key,
collection: this
) => key is NewKey,
thisArg: This
): Collection<NewKey, Value>;
<This, NewValue extends Value>(
fn: (
this: This,
value: Value,
key: Key,
collection: this
) => value is NewValue,
thisArg: This
): Collection<Key, NewValue>;
<This>(
fn: (this: This, value: Value, key: Key, collection: this) => unknown,
thisArg: This
): Collection<Key, Value>;
};
  • Identical to Array.filter(), but returns a Collection instead of an Array.

    Parameter fn

    The function to test with (should return a boolean)

    Parameter thisArg

    Value to use as this when executing the function

    Example 1

    collection.filter(user => user.username === 'Bob');

method find

find: {
<NewValue extends Value>(
fn: (value: Value, key: Key, collection: this) => value is NewValue
): NewValue | undefined;
(fn: (value: Value, key: Key, collection: this) => unknown): Value;
<This, NewValue extends Value>(
fn: (
this: This,
value: Value,
key: Key,
collection: this
) => value is NewValue,
thisArg: This
): NewValue;
<This>(
fn: (this: This, value: Value, key: Key, collection: this) => unknown,
thisArg: This
): Value;
};
  • Searches for a single item where the given function returns a truthy value. This behaves like Array.find(). All collections used in Discord.js are mapped using their id property, and if you want to find by id you should use the get method. See MDN for details.

    Parameter fn

    The function to test with (should return a boolean)

    Parameter thisArg

    Value to use as this when executing the function

    Example 1

    collection.find(user => user.username === 'Bob');

method findKey

findKey: {
<NewKey extends Key>(
fn: (value: Value, key: Key, collection: this) => key is NewKey
): NewKey | undefined;
(fn: (value: Value, key: Key, collection: this) => unknown): Key;
<This, NewKey extends Key>(
fn: (
this: This,
value: Value,
key: Key,
collection: this
) => key is NewKey,
thisArg: This
): NewKey;
<This>(
fn: (this: This, value: Value, key: Key, collection: this) => unknown,
thisArg: This
): Key;
};
  • Searches for the key of a single item where the given function returns a truthy value. This behaves like Array.findIndex(), but returns the key rather than the positional index.

    Parameter fn

    The function to test with (should return a boolean)

    Parameter thisArg

    Value to use as this when executing the function

    Example 1

    collection.findKey(user => user.username === 'Bob');

method findLast

findLast: {
<NewValue extends Value>(
fn: (value: Value, key: Key, collection: this) => value is NewValue
): NewValue | undefined;
(fn: (value: Value, key: Key, collection: this) => unknown): Value;
<This, NewValue extends Value>(
fn: (
this: This,
value: Value,
key: Key,
collection: this
) => value is NewValue,
thisArg: This
): NewValue;
<This>(
fn: (this: This, value: Value, key: Key, collection: this) => unknown,
thisArg: This
): Value;
};
  • Searches for a last item where the given function returns a truthy value. This behaves like Array.findLast().

    Parameter fn

    The function to test with (should return a boolean)

    Parameter thisArg

    Value to use as this when executing the function

method findLastKey

findLastKey: {
<NewKey extends Key>(
fn: (value: Value, key: Key, collection: this) => key is NewKey
): NewKey | undefined;
(fn: (value: Value, key: Key, collection: this) => unknown): Key;
<This, NewKey extends Key>(
fn: (
this: This,
value: Value,
key: Key,
collection: this
) => key is NewKey,
thisArg: This
): NewKey;
<This>(
fn: (this: This, value: Value, key: Key, collection: this) => unknown,
thisArg: This
): Key;
};
  • Searches for the key of a last item where the given function returns a truthy value. This behaves like Array.findLastIndex(), but returns the key rather than the positional index.

    Parameter fn

    The function to test with (should return a boolean)

    Parameter thisArg

    Value to use as this when executing the function

method first

first: { (): Value | undefined; (amount: number): Value[] };
  • Obtains the first value(s) in this collection.

    Parameter amount

    Amount of values to obtain from the beginning

    Returns

    A single value if no amount is provided or an array of values, starting from the end if amount is negative

method firstKey

firstKey: { (): Key | undefined; (amount: number): Key[] };
  • Obtains the first key(s) in this collection.

    Parameter amount

    Amount of keys to obtain from the beginning

    Returns

    A single key if no amount is provided or an array of keys, starting from the end if amount is negative

method flatMap

flatMap: {
<NewValue>(
fn: (
value: Value,
key: Key,
collection: this
) => Collection<Key, NewValue>
): Collection<Key, NewValue>;
<NewValue, This>(
fn: (
this: This,
value: Value,
key: Key,
collection: this
) => Collection<Key, NewValue>,
thisArg: This
): Collection<Key, NewValue>;
};
  • Maps each item into a Collection, then joins the results into a single Collection. Identical in behavior to Array.flatMap().

    Parameter fn

    Function that produces a new Collection

    Parameter thisArg

    Value to use as this when executing the function

    Example 1

    collection.flatMap(guild => guild.members.cache);

method hasAll

hasAll: (...keys: Key[]) => boolean;
  • Checks if all of the elements exist in the collection.

    Parameter keys

    The keys of the elements to check for

    Returns

    true if all of the elements exist, false if at least one does not exist.

method hasAny

hasAny: (...keys: Key[]) => boolean;
  • Checks if any of the elements exist in the collection.

    Parameter keys

    The keys of the elements to check for

    Returns

    true if any of the elements exist, false if none exist.

method intersection

intersection: (other: ReadonlyCollection<Key, any>) => Collection<Key, Value>;
  • The intersection method returns a new collection containing the items where the key is present in both collections.

    Parameter other

    The other Collection to filter against

    Example 1

    const col1 = new Collection([['a', 1], ['b', 2]]);
    const col2 = new Collection([['a', 1], ['c', 3]]);
    const intersection = col1.intersection(col2);
    console.log(col1.intersection(col2));
    // => Collection { 'a' => 1 }

method keyAt

keyAt: (index: number) => Key | undefined;
  • Identical to Array.at(). Returns the key at a given index, allowing for positive and negative integers. Negative integers count back from the last item in the collection.

    Parameter index

    The index of the key to obtain

method last

last: { (): Value | undefined; (amount: number): Value[] };
  • Obtains the last value(s) in this collection.

    Parameter amount

    Amount of values to obtain from the end

    Returns

    A single value if no amount is provided or an array of values, starting from the start if amount is negative

method lastKey

lastKey: { (): Key | undefined; (amount: number): Key[] };
  • Obtains the last key(s) in this collection.

    Parameter amount

    Amount of keys to obtain from the end

    Returns

    A single key if no amount is provided or an array of keys, starting from the start if amount is negative

method map

map: {
<NewValue>(
fn: (value: Value, key: Key, collection: this) => NewValue
): NewValue[];
<This, NewValue>(
fn: (this: This, value: Value, key: Key, collection: this) => NewValue,
thisArg: This
): NewValue[];
};
  • Maps each item to another value into an array. Identical in behavior to Array.map().

    Parameter fn

    Function that produces an element of the new array, taking three arguments

    Parameter thisArg

    Value to use as this when executing the function

    Example 1

    collection.map(user => user.tag);

method mapValues

mapValues: {
<NewValue>(
fn: (value: Value, key: Key, collection: this) => NewValue
): Collection<Key, NewValue>;
<This, NewValue>(
fn: (this: This, value: Value, key: Key, collection: this) => NewValue,
thisArg: This
): Collection<Key, NewValue>;
};
  • Maps each item to another value into a collection. Identical in behavior to Array.map().

    Parameter fn

    Function that produces an element of the new collection, taking three arguments

    Parameter thisArg

    Value to use as this when executing the function

    Example 1

    collection.mapValues(user => user.tag);

method merge

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>;
  • Merges two Collections together into a new Collection.

    Parameter other

    The other Collection to merge with

    Parameter whenInSelf

    Function getting the result if the entry only exists in this Collection

    Parameter whenInOther

    Function getting the result if the entry only exists in the other Collection

    Parameter whenInBoth

    Function getting the result if the entry exists in both Collections

    Example 1

    // Sums up the entries in two collections.
    coll.merge(
    other,
    x => ({ keep: true, value: x }),
    y => ({ keep: true, value: y }),
    (x, y) => ({ keep: true, value: x + y }),
    );

    Example 2

    // Intersects two collections in a left-biased manner.
    coll.merge(
    other,
    x => ({ keep: false }),
    y => ({ keep: false }),
    (x, _) => ({ keep: true, value: x }),
    );

method partition

partition: {
<NewKey extends Key>(
fn: (value: Value, key: Key, collection: this) => key is NewKey
): [Collection<NewKey, Value>, Collection<Exclude<Key, NewKey>, Value>];
<NewValue extends Value>(
fn: (value: Value, key: Key, collection: this) => value is NewValue
): [Collection<Key, NewValue>, Collection<Key, Exclude<Value, NewValue>>];
(fn: (value: Value, key: Key, collection: this) => unknown): [
Collection<Key, Value>,
Collection<Key, Value>
];
<This, NewKey extends Key>(
fn: (
this: This,
value: Value,
key: Key,
collection: this
) => key is NewKey,
thisArg: This
): [Collection<NewKey, Value>, Collection<Exclude<Key, NewKey>, Value>];
<This, NewValue extends Value>(
fn: (
this: This,
value: Value,
key: Key,
collection: this
) => value is NewValue,
thisArg: This
): [Collection<Key, NewValue>, Collection<Key, Exclude<Value, NewValue>>];
<This>(
fn: (this: This, value: Value, key: Key, collection: this) => unknown,
thisArg: This
): [Collection<Key, Value>, Collection<Key, Value>];
};
  • Partitions the collection into two collections where the first collection contains the items that passed and the second contains the items that failed.

    Parameter fn

    Function used to test (should return a boolean)

    Parameter thisArg

    Value to use as this when executing the function

    Example 1

    const [big, small] = collection.partition(guild => guild.memberCount > 250);

method random

random: { (): Value | undefined; (amount: number): Value[] };
  • Obtains unique random value(s) from this collection.

    Parameter amount

    Amount of values to obtain randomly

    Returns

    A single value if no amount is provided or an array of values

method randomKey

randomKey: { (): Key | undefined; (amount: number): Key[] };
  • Obtains unique random key(s) from this collection.

    Parameter amount

    Amount of keys to obtain randomly

    Returns

    A single key if no amount is provided or an array

method reduce

reduce: <InitialValue = Value>(
fn: (
accumulator: InitialValue,
value: Value,
key: Key,
collection: this
) => InitialValue,
initialValue?: InitialValue
) => InitialValue;
  • Applies a function to produce a single value. Identical in behavior to Array.reduce().

    Parameter fn

    Function used to reduce, taking four arguments; accumulator, currentValue, currentKey, and collection

    Parameter initialValue

    Starting value for the accumulator

    Example 1

    collection.reduce((acc, guild) => acc + guild.memberCount, 0);

method reduceRight

reduceRight: <InitialValue>(
fn: (
accumulator: InitialValue,
value: Value,
key: Key,
collection: this
) => InitialValue,
initialValue?: InitialValue
) => InitialValue;
  • Applies a function to produce a single value. Identical in behavior to Array.reduceRight().

    Parameter fn

    Function used to reduce, taking four arguments; accumulator, value, key, and collection

    Parameter initialValue

    Starting value for the accumulator

method reverse

reverse: () => this;

method some

some: {
(fn: (value: Value, key: Key, collection: this) => unknown): boolean;
<This>(
fn: (this: This, value: Value, key: Key, collection: this) => unknown,
thisArg: This
): boolean;
};
  • Checks if there exists an item that passes a test. Identical in behavior to Array.some().

    Parameter fn

    Function used to test (should return a boolean)

    Parameter thisArg

    Value to use as this when executing the function

    Example 1

    collection.some(user => user.discriminator === '0000');

method sort

sort: (compareFunction?: Comparator<Key, Value>) => 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.

    Parameter compareFunction

    Specifies a function that defines the sort order. If omitted, the collection is sorted according to each character's Unicode code point value, according to the string conversion of each element.

    Example 1

    collection.sort((userA, userB) => userA.createdTimestamp - userB.createdTimestamp);

method sweep

sweep: {
(fn: (value: Value, key: Key, collection: this) => unknown): number;
<This>(
fn: (this: This, value: Value, key: Key, collection: this) => unknown,
thisArg: This
): number;
};
  • Removes items that satisfy the provided filter function.

    Parameter fn

    Function used to test (should return a boolean)

    Parameter thisArg

    Value to use as this when executing the function

    Returns

    The number of removed entries

method symmetricDifference

symmetricDifference: <OtherValue>(
other: ReadonlyCollection<Key, OtherValue>
) => Collection<Key, OtherValue | Value>;
  • Returns a new collection containing only the items where the keys are present in either collection, but not both.

    Parameter other

    The other Collection to filter against

    Example 1

    const col1 = new Collection([['a', 1], ['b', 2]]);
    const col2 = new Collection([['a', 1], ['c', 3]]);
    const symmetricDifference = col1.symmetricDifference(col2);
    console.log(col1.symmetricDifference(col2));
    // => Collection { 'b' => 2, 'c' => 3 }

method tap

tap: {
(fn: (collection: this) => void): this;
<This>(fn: (this: This, collection: this) => void, thisArg: This): this;
};
  • Runs a function on the collection and returns the collection.

    Parameter fn

    Function to execute

    Parameter thisArg

    Value to use as this when executing the function

    Example 1

    collection
    .tap(coll => console.log(coll.size))
    .filter(user => user.bot)
    .tap(coll => console.log(coll.size))

method toJSON

toJSON: () => [Key, Value][];

    method toReversed

    toReversed: () => Collection<Key, Value>;

    method toSorted

    toSorted: (compareFunction?: Comparator<Key, Value>) => Collection<Key, Value>;
    • The sorted method sorts the items of a collection 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.

      Parameter compareFunction

      Specifies a function that defines the sort order. If omitted, the collection is sorted according to each character's Unicode code point value, according to the string conversion of each element.

      Example 1

      collection.sorted((userA, userB) => userA.createdTimestamp - userB.createdTimestamp);

    method union

    union: <OtherValue>(
    other: ReadonlyCollection<Key, OtherValue>
    ) => Collection<Key, OtherValue | Value>;
    • Returns a new collection containing the items where the key is present in either of the collections.

      Parameter other

      The other Collection to filter against

      Remarks

      If the collections have any items with the same key, the value from the first collection will be used.

      Example 1

      const col1 = new Collection([['a', 1], ['b', 2]]);
      const col2 = new Collection([['a', 1], ['b', 3], ['c', 3]]);
      const union = col1.union(col2);
      console.log(union);
      // => Collection { 'a' => 1, 'b' => 2, 'c' => 3 }

    Type Aliases

    type ReadonlyCollection

    type ReadonlyCollection<Key, Value> = Omit<
    Collection<Key, Value>,
    'delete' | 'ensure' | 'forEach' | 'get' | 'reverse' | 'set' | 'sort' | 'sweep'
    > &
    ReadonlyMap<Key, Value>;
    • Represents an immutable version of a collection

    Package Files (1)

    Dependencies (0)

    No dependencies.

    Dev Dependencies (14)

    Peer Dependencies (0)

    No peer dependencies.

    Badge

    To add a badge like this onejsDocs.io badgeto your package's README, use the codes available below.

    You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/@discordjs/collection.

    • Markdown
      [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/@discordjs/collection)
    • HTML
      <a href="https://www.jsdocs.io/package/@discordjs/collection"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>