• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

WolferyScripting / resclient-ts / #25

24 Aug 2025 12:37PM UTC coverage: 51.153% (+0.9%) from 50.293%
#25

push

DonovanDMC
1.1.0

227 of 281 branches covered (80.78%)

Branch coverage included in aggregate %.

1570 of 3232 relevant lines covered (48.58%)

10.67 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

64.52
/lib/models/ResCollection.ts
1
import type ResClient from "./ResClient.js";
1✔
2
import type CacheItem from "./CacheItem.js";
1✔
3
import { copy } from "../includes/utils/obj.js";
1✔
4
import Properties from "../util/Properties.js";
1✔
5
import { type AnyObject, type AnyFunction } from "../util/types.js";
1✔
6

1✔
7
export default class ResCollection<V = unknown> {
1✔
8
    private _idCallback?: (item: V) => string;
12✔
9
    private _list: Array<V> = [];
12✔
10
    private _map!: Record<string, V> | null;
12✔
11
    protected api!: ResClient;
12✔
12
    rid!: string;
12✔
13
    constructor(api: ResClient, rid: string, options?: { idCallback?(item: V): string; }) {
12✔
14
        options = copy(options ?? {}, {
12✔
15
            idCallback: { type: "?function" }
12✔
16
        });
12✔
17
        this.p
12✔
18
            .writableBulk(["_idCallback", options?.idCallback?.bind(this)], "_list", ["_map", options.idCallback ? {} : null])
12✔
19
            .readOnly("api", api)
12✔
20
            .define("rid", false, true, true, rid);
12✔
21
    }
12✔
22

12✔
23
    private _hasID(): void {
12✔
24
        if (!this._idCallback) {
14!
25
            throw new Error("No id callback defined");
×
26
        }
×
27
    }
14✔
28

12✔
29
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
12✔
30
    protected async _listen(on: boolean): Promise<void> {
12✔
31
        // empty
12✔
32
    }
12✔
33

12✔
34
    protected get p(): Properties {
12✔
35
        return Properties.of(this);
12✔
36
    }
12✔
37

12✔
38
    get cacheItem(): CacheItem<ResCollection> {
12✔
39
        return this.getClient().cache[this.rid] as CacheItem<ResCollection>;
×
40
    }
×
41

12✔
42
    /** If this collection is empty. */
12✔
43
    get empty(): boolean {
12✔
44
        return this.length === 0;
×
45
    }
×
46

12✔
47
    get length(): number {
12✔
48
        return this._list.length;
×
49
    }
×
50

12✔
51
    get list(): Array<V> {
12✔
52
        return this._list;
×
53
    }
×
54

12✔
55
    [Symbol.iterator](): Iterator<V, undefined> {
12✔
56
        return this._list[Symbol.iterator]();
×
57
    }
×
58

12✔
59
    add(item: V, index: number): void {
12✔
60
        this._list.splice(index, 0, item);
3✔
61

3✔
62
        if (this._idCallback) {
3✔
63
            const id = String(this._idCallback(item));
2✔
64
            if (["", "undefined", "null"].includes(id) || id.replaceAll(/\W/g, "") === "") {
2!
65
                console.debug(item);
×
66
                throw new Error("No id for item");
×
67
            }
×
68
            if (this._map![id]) {
2✔
69
                throw new Error(`Duplicate id - ${id}`);
1✔
70
            }
1✔
71
            this._map![id] = item;
1✔
72
        }
1✔
73
    }
3✔
74

12✔
75
    at(index: number): V | undefined {
12✔
76
        return this._list[index];
14✔
77
    }
14✔
78

12✔
79
    auth<T = unknown>(method: string, params: unknown): Promise<T> {
12✔
80
        return this.api.authenticate<T>(this.rid, method, params);
×
81
    }
×
82

12✔
83
    call<T = unknown>(method: string, params: unknown): Promise<T> {
12✔
84
        return this.api.call<T>(this.rid, method, params);
×
85
    }
×
86

12✔
87
    /** Called when the collection is unsubscribed. */
12✔
88
    async dispose(): Promise<void> {
12✔
89
        await this._listen(false);
×
90
    }
×
91

12✔
92
    /** See: {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every | Array#every } */
12✔
93
    every<T extends V, ThisArg = ResCollection<V>>(predicate: (value: V, index: number, array: Array<V>) => value is T, thisArg?: ThisArg): this is Array<T>;
12✔
94
    every<ThisArg = ResCollection<V>>(predicate: (value: V, index: number, array: Array<V>) => unknown, thisArg?: ThisArg): boolean;
12✔
95
    every(predicate: (value: V, index: number, array: Array<V>) => unknown, thisArg?: unknown): boolean {
12✔
96
        return this.toArray().every(predicate, thisArg);
×
97

×
98
    }
×
99

12✔
100
    /** See: {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter | Array#filter } */
12✔
101
    filter<S extends V, ThisArg = ResCollection<V>>(predicate: (this: ThisArg, value: V, index: number, array: Array<V>) => value is S, thisArg?: ThisArg): Array<S>;
12✔
102
    filter<ThisArg = ResCollection<V>>(predicate: (this: ThisArg, value: V, index: number, array: Array<V>) => unknown, thisArg?: ThisArg): Array<V>;
12✔
103
    filter(predicate: (value: V, index: number, array: Array<V>) => unknown, thisArg?: unknown): Array<V> {
12✔
104
        return this.toArray().filter(predicate, thisArg) ;
×
105
    }
×
106

12✔
107
    /** See: {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find | Array#find } */
12✔
108
    find<S extends V, ThisArg = ResCollection<V>>(predicate: (this: ThisArg, value: V, index: number, obj: Array<V>) => value is S, thisArg?: ThisArg): S | undefined;
12✔
109
    find<ThisArg = ResCollection<V>>(predicate: (this: ThisArg, value: V, index: number, obj: Array<V>) => unknown, thisArg?: ThisArg): V | undefined;
12✔
110
    find(predicate: (value: V, index: number, obj: Array<V>) => unknown, thisArg?: unknown): V | undefined {
12✔
111
        return this.toArray().find(predicate, thisArg);
×
112
    }
×
113

12✔
114
    /** See: {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex | Array#findIndex } */
12✔
115
    findIndex(predicate: (value: V, index: number, obj: Array<V>) => unknown, thisArg?: unknown): number {
12✔
116
        return this.toArray().findIndex(predicate, thisArg);
×
117
    }
×
118

12✔
119
    /**
12✔
120
     * Get the first element, or first X elements if a number is provided.
12✔
121
     * @param amount The amount of elements to get.
12✔
122
     */
12✔
123
    first(): V | undefined;
12✔
124
    first(amount: number): Array<V>;
12✔
125
    first(amount?: number): V | Array<V> | undefined {
12✔
126
        if (amount === undefined) {
×
127
            const iterable = this[Symbol.iterator]();
×
128
            return iterable.next().value;
×
129
        }
×
130

×
131
        if (amount < 0) {
×
132
            return this.last(amount * -1);
×
133
        }
×
134
        amount = Math.min(amount, this.length);
×
135

×
136
        const iterable = this[Symbol.iterator]();
×
137
        return Array.from({ length: amount }, () => iterable.next().value!);
×
138
    }
×
139

12✔
140
    get(id: string | number): V | undefined {
12✔
141
        this._hasID();
14✔
142
        return this._map![id];
14✔
143
    }
14✔
144

12✔
145
    getClient(): ResClient {
12✔
146
        return this.api;
×
147
    }
×
148

12✔
149
    getOrThrow(id: string | number): V {
12✔
150
        const item = this.get(id);
×
151
        if (item === undefined) {
×
152
            throw new TypeError(`${id} not found in ${this.rid}`);
×
153
        }
×
154

×
155
        return item;
×
156
    }
×
157

12✔
158
    indexOf(item: V): number {
12✔
159
        return this._list.indexOf(item);
×
160
    }
×
161

12✔
162
    async init(data: Array<V> = []): Promise<this> {
12✔
163
        this._list = data;
12✔
164

12✔
165
        if (this._idCallback) {
12✔
166
            this._map = {};
6✔
167
            for (const v of this._list) {
6✔
168
                const id = String(this._idCallback(v));
18✔
169
                if (["", "undefined", "null"].includes(id) || id.replaceAll(/\W/g, "") === "") {
18!
170
                    throw new Error("No id for item");
×
171
                }
×
172
                if (this._map[id]) {
18!
173
                    throw new Error(`Duplicate id - ${id}`);
×
174
                }
×
175
                this._map[id] = v;
18✔
176
            }
18✔
177
        }
6✔
178
        await this._listen(true);
12✔
179

12✔
180
        return this;
12✔
181
    }
12✔
182

12✔
183
    /**
12✔
184
     * Get the last element, or last X elements if a number is provided.
12✔
185
     * @param amount The amount of elements to get.
12✔
186
     */
12✔
187
    last(): V | undefined;
12✔
188
    last(amount: number): Array<V>;
12✔
189
    last(amount?: number): V | Array<V> | undefined {
12✔
190
        const iterator = Array.from(this._list);
×
191
        if (amount === undefined) {
×
192
            return iterator.at(-1);
×
193
        }
×
194
        if (amount < 0) {
×
195
            return this.first(amount * -1);
×
196
        }
×
197
        if (!amount) {
×
198
            return [];
×
199
        }
×
200

×
201
        return iterator.slice(-amount);
×
202
    }
×
203

12✔
204
    /** See: {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map | Array#map } */
12✔
205
    map<T>(predicate: (value: V, index: number, obj: Array<V>) => T, thisArg?: unknown): Array<T> {
12✔
206
        return this.toArray().map(predicate, thisArg);
×
207
    }
×
208

12✔
209
    off(events: string | Array<string> | null, handler: AnyFunction): this {
12✔
210
        this.api.eventBus.off(this, events, handler);
×
211
        return this;
×
212
    }
×
213

12✔
214
    on(events: string | Array<string> | null, handler: AnyFunction): this {
12✔
215
        this.api.eventBus.on(this, events, handler);
×
216
        return this;
×
217
    }
×
218

12✔
219
    /**
12✔
220
     * Pick a random element from the collection, or undefined if the collection is empty.
12✔
221
     */
12✔
222
    random(): V | undefined {
12✔
223
        if (this.empty) {
×
224
            return undefined;
×
225
        }
×
226
        const iterable = Array.from(this._list);
×
227

×
228
        return iterable[Math.floor(Math.random() * iterable.length)];
×
229
    }
×
230

12✔
231
    /** See: {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce | Array#reduce } */
12✔
232
    reduce(predicate: (previousValue: V, currentValue: V, currentIndex: number, array: Array<V>) => V): V;
12✔
233
    reduce(predicate: (previousValue: V, currentValue: V, currentIndex: number, array: Array<V>) => V, initialValue: V): V;
12✔
234
    reduce<T>(predicate: (previousValue: T, currentValue: V, currentIndex: number, array: Array<V>) => T, initialValue: T): T;
12✔
235
    reduce<T>(predicate: (previousValue: T, currentValue: V, currentIndex: number, array: Array<V>) => T, initialValue?: T): T {
12✔
236
        return this.toArray().reduce(predicate, initialValue!);
×
237
    }
×
238

12✔
239
    /** See: {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight | Array#reduceRight } */
12✔
240
    reduceRight(predicate: (previousValue: V, currentValue: V, currentIndex: number, array: Array<V>) => V): V;
12✔
241
    reduceRight(predicate: (previousValue: V, currentValue: V, currentIndex: number, array: Array<V>) => V, initialValue: V): V;
12✔
242
    reduceRight<T>(predicate: (previousValue: T, currentValue: V, currentIndex: number, array: Array<V>) => T, initialValue: T): T;
12✔
243
    reduceRight<T>(predicate: (previousValue: T, currentValue: V, currentIndex: number, array: Array<V>) => T, initialValue?: T): T {
12✔
244
        return this.toArray().reduceRight(predicate, initialValue!);
×
245
    }
×
246

12✔
247
    remove(index: number): V | undefined {
12✔
248
        const item = this._list[index];
2✔
249
        if (item !== undefined) {
2✔
250
            this._list.splice(index, 1);
2✔
251

2✔
252
            if (this._idCallback) {
2✔
253
                delete this._map![this._idCallback(item)];
1✔
254
            }
1✔
255
        }
2✔
256

2✔
257
        return item;
2✔
258
    }
2✔
259

12✔
260
    resourceOff(events: string | Array<string> | null, handler: AnyFunction): this {
12✔
261
        this.api.resourceOff(this.rid, events, handler);
×
262
        return this;
×
263
    }
×
264

12✔
265
    resourceOn(events: string | Array<string> | null, handler: AnyFunction): this {
12✔
266
        this.api.resourceOn(this.rid, events, handler);
×
267
        return this;
×
268
    }
×
269

12✔
270
    /** See: {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some | Array#some } */
12✔
271
    some<ThisArg = ResCollection<V>>(predicate: (value: V, index: number, array: Array<V>) => unknown, thisArg?: ThisArg): boolean {
12✔
272
        return this.toArray().some(predicate, thisArg);
×
273
    }
×
274

12✔
275
    /** Get the values of this collection as an array. */
12✔
276
    toArray(): Array<V> {
12✔
277
        return Array.from(this._list);
×
278
    }
×
279

12✔
280
    toJSON(): Array<unknown> {
12✔
281
        return this._list.map(v => (
×
282
            v !== null && typeof v === "object" && "toJSON" in v
×
283
                ? (v as { toJSON(): AnyObject; }).toJSON()
×
284
                : v
×
285
        ));
×
286
    }
×
287
}
12✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc