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

WolferyScripting / resclient-ts / #33

27 Aug 2025 09:08PM UTC coverage: 51.192% (+0.3%) from 50.87%
#33

push

DonovanDMC
1.1.4

230 of 292 branches covered (78.77%)

Branch coverage included in aggregate %.

1660 of 3400 relevant lines covered (48.82%)

10.5 hits per line

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

64.55
/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 interface ResCollectionEvents<V = unknown> {
1✔
8
    add: [data: CollectionAddRemove<V>];
1✔
9
    remove: [data: CollectionAddRemove<V>];
1✔
10
}
1✔
11
export interface CollectionAddRemove<V> { idx: number; item: V; }
1✔
12
export default class ResCollection<V = unknown, ResourceEvents extends { [K in keyof ResourceEvents]: Array<unknown> } = ResCollectionEvents<V>, ModelEvents extends { [K in keyof ModelEvents]: Array<unknown> } = Record<string, Array<unknown>>> {
1✔
13
    private _idCallback?: (item: V) => string;
12✔
14
    private _list: Array<V> = [];
12✔
15
    private _map!: Record<string, V> | null;
12✔
16
    protected api!: ResClient;
12✔
17
    rid!: string;
12✔
18
    constructor(api: ResClient, rid: string, options?: { idCallback?(item: V): string; }) {
12✔
19
        options = copy(options ?? {}, {
12✔
20
            idCallback: { type: "?function" }
12✔
21
        });
12✔
22
        this.p
12✔
23
            .writableBulk(["_idCallback", options?.idCallback?.bind(this)], "_list", ["_map", options.idCallback ? {} : null])
12✔
24
            .readOnly("api", api)
12✔
25
            .define("rid", false, true, true, rid);
12✔
26
    }
12✔
27

12✔
28
    private _hasID(): void {
12✔
29
        if (!this._idCallback) {
14!
30
            throw new Error("No id callback defined");
×
31
        }
×
32
    }
14✔
33

12✔
34
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
12✔
35
    protected async _listen(on: boolean): Promise<void> {
12✔
36
        // empty
×
37
    }
×
38

12✔
39
    protected get p(): Properties {
12✔
40
        return Properties.of(this);
12✔
41
    }
12✔
42

12✔
43
    get cacheItem(): CacheItem<ResCollection> {
12✔
44
        return this.getClient().cache[this.rid] as CacheItem<ResCollection>;
×
45
    }
×
46

12✔
47
    /** If this collection is empty. */
12✔
48
    get empty(): boolean {
12✔
49
        return this.length === 0;
×
50
    }
×
51

12✔
52
    get length(): number {
12✔
53
        return this._list.length;
×
54
    }
×
55

12✔
56
    get list(): Array<V> {
12✔
57
        return this._list;
×
58
    }
×
59

12✔
60
    [Symbol.iterator](): Iterator<V, undefined> {
12✔
61
        return this._list[Symbol.iterator]();
×
62
    }
×
63

12✔
64
    add(item: V, index: number): void {
12✔
65
        this._list.splice(index, 0, item);
3✔
66

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

12✔
80
    at(index: number): V | undefined {
12✔
81
        return this._list[index];
14✔
82
    }
14✔
83

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

12✔
88
    call<T = unknown>(method: string, params?: unknown): Promise<T> {
12✔
89
        return this.api.call<T>(this.rid, method, params);
×
90
    }
×
91

12✔
92
    /** Called when the collection is unsubscribed. */
12✔
93
    async dispose(): Promise<void> {
12✔
94
        await this._listen(false);
×
95
    }
×
96

12✔
97
    /** See: {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every | Array#every } */
12✔
98
    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✔
99
    every<ThisArg = ResCollection<V>>(predicate: (value: V, index: number, array: Array<V>) => unknown, thisArg?: ThisArg): boolean;
12✔
100
    every(predicate: (value: V, index: number, array: Array<V>) => unknown, thisArg?: unknown): boolean {
12✔
101
        return this.toArray().every(predicate, thisArg);
×
102

×
103
    }
×
104

12✔
105
    /** See: {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter | Array#filter } */
12✔
106
    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✔
107
    filter<ThisArg = ResCollection<V>>(predicate: (this: ThisArg, value: V, index: number, array: Array<V>) => unknown, thisArg?: ThisArg): Array<V>;
12✔
108
    filter(predicate: (value: V, index: number, array: Array<V>) => unknown, thisArg?: unknown): Array<V> {
12✔
109
        return this.toArray().filter(predicate, thisArg) ;
×
110
    }
×
111

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

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

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

×
136
        if (amount < 0) {
×
137
            return this.last(amount * -1);
×
138
        }
×
139
        amount = Math.min(amount, this.length);
×
140

×
141
        const iterable = this[Symbol.iterator]();
×
142
        return Array.from({ length: amount }, () => iterable.next().value!);
×
143
    }
×
144

12✔
145
    get(id: string | number): V | undefined {
12✔
146
        this._hasID();
14✔
147
        return this._map![id];
14✔
148
    }
14✔
149

12✔
150
    getClient(): ResClient {
12✔
151
        return this.api;
×
152
    }
×
153

12✔
154
    getOrThrow(id: string | number): V {
12✔
155
        const item = this.get(id);
×
156
        if (item === undefined) {
×
157
            throw new TypeError(`${id} not found in ${this.rid}`);
×
158
        }
×
159

×
160
        return item;
×
161
    }
×
162

12✔
163
    has(item: V): boolean {
12✔
164
        return this._list.includes(item);
×
165
    }
×
166

12✔
167
    hasKey(key: string | number): boolean {
12✔
168
        this._hasID();
×
169
        return key in this._map!;
×
170
    }
×
171

12✔
172
    indexOf(item: V): number {
12✔
173
        return this._list.indexOf(item);
×
174
    }
×
175

12✔
176
    async init(data: Array<V> = []): Promise<this> {
12✔
177
        this._list = data;
12✔
178

12✔
179
        if (this._idCallback) {
12✔
180
            this._map = {};
6✔
181
            for (const v of this._list) {
6✔
182
                const id = String(this._idCallback(v));
18✔
183
                if (["", "undefined", "null"].includes(id) || id.replaceAll(/\W/g, "") === "") {
18!
184
                    throw new Error("No id for item");
×
185
                }
×
186
                if (this._map[id]) {
18!
187
                    throw new Error(`Duplicate id - ${id}`);
×
188
                }
×
189
                this._map[id] = v;
18✔
190
            }
18✔
191
        }
6✔
192

12✔
193
        return this;
12✔
194
    }
12✔
195

12✔
196
    /**
12✔
197
     * Get the last element, or last X elements if a number is provided.
12✔
198
     * @param amount The amount of elements to get.
12✔
199
     */
12✔
200
    last(amount?: undefined): V | undefined;
12✔
201
    last(amount: number): Array<V>;
12✔
202
    last(amount?: number): V | Array<V> | undefined {
12✔
203
        const iterator = Array.from(this._list);
×
204
        if (amount === undefined) {
×
205
            return iterator.at(-1);
×
206
        }
×
207
        if (amount < 0) {
×
208
            return this.first(amount * -1);
×
209
        }
×
210
        if (!amount) {
×
211
            return [];
×
212
        }
×
213

×
214
        return iterator.slice(-amount);
×
215
    }
×
216

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

12✔
222
    off<K extends keyof ModelEvents>(event: K, handler: (...args: ModelEvents[K]) => void): this;
12✔
223
    off(events: string | Array<string> | null, handler: AnyFunction): this;
12✔
224
    off(events: string | Array<string> | null, handler: AnyFunction): this {
12✔
225
        this.api.eventBus.off(this, events, handler);
×
226
        return this;
×
227
    }
×
228

12✔
229
    on<K extends keyof ModelEvents>(event: K, handler: (...args: ModelEvents[K]) => void): this;
12✔
230
    on(events: string | Array<string> | null, handler: AnyFunction): this;
12✔
231
    on(events: string | Array<string> | null, handler: AnyFunction): this {
12✔
232
        this.api.eventBus.on(this, events, handler);
×
233
        return this;
×
234
    }
×
235

12✔
236
    /**
12✔
237
     * Pick a random element from the collection, or undefined if the collection is empty.
12✔
238
     */
12✔
239
    random(): V | undefined {
12✔
240
        if (this.empty) {
×
241
            return undefined;
×
242
        }
×
243
        const iterable = Array.from(this._list);
×
244

×
245
        return iterable[Math.floor(Math.random() * iterable.length)];
×
246
    }
×
247

12✔
248
    /** See: {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce | Array#reduce } */
12✔
249
    reduce(predicate: (previousValue: V, currentValue: V, currentIndex: number, array: Array<V>) => V): V;
12✔
250
    reduce(predicate: (previousValue: V, currentValue: V, currentIndex: number, array: Array<V>) => V, initialValue: V): V;
12✔
251
    reduce<T>(predicate: (previousValue: T, currentValue: V, currentIndex: number, array: Array<V>) => T, initialValue: T): T;
12✔
252
    reduce<T>(predicate: (previousValue: T, currentValue: V, currentIndex: number, array: Array<V>) => T, initialValue?: T): T {
12✔
253
        return this.toArray().reduce(predicate, initialValue!);
×
254
    }
×
255

12✔
256
    /** See: {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight | Array#reduceRight } */
12✔
257
    reduceRight(predicate: (previousValue: V, currentValue: V, currentIndex: number, array: Array<V>) => V): V;
12✔
258
    reduceRight(predicate: (previousValue: V, currentValue: V, currentIndex: number, array: Array<V>) => V, initialValue: V): V;
12✔
259
    reduceRight<T>(predicate: (previousValue: T, currentValue: V, currentIndex: number, array: Array<V>) => T, initialValue: T): T;
12✔
260
    reduceRight<T>(predicate: (previousValue: T, currentValue: V, currentIndex: number, array: Array<V>) => T, initialValue?: T): T {
12✔
261
        return this.toArray().reduceRight(predicate, initialValue!);
×
262
    }
×
263

12✔
264
    remove(index: number): V | undefined {
12✔
265
        const item = this._list[index];
2✔
266
        if (item !== undefined) {
2✔
267
            this._list.splice(index, 1);
2✔
268

2✔
269
            if (this._idCallback) {
2✔
270
                delete this._map![this._idCallback(item)];
1✔
271
            }
1✔
272
        }
2✔
273

2✔
274
        return item;
2✔
275
    }
2✔
276

12✔
277
    resourceOff<K extends keyof ResourceEvents>(event: K, handler: (...args: ResourceEvents[K]) => void): this;
12✔
278
    resourceOff(events: string | Array<string> | null, handler: AnyFunction): this;
12✔
279
    resourceOff(events: string | Array<string> | null, handler: AnyFunction): this {
12✔
280
        this.api.resourceOff(this.rid, events, handler);
×
281
        return this;
×
282
    }
×
283

12✔
284
    resourceOn<K extends keyof ResourceEvents>(event: K, handler: (...args: ResourceEvents[K]) => void): this;
12✔
285
    resourceOn(events: string | Array<string> | null, handler: AnyFunction): this;
12✔
286
    resourceOn(events: string | Array<string> | null, handler: AnyFunction): this {
12✔
287
        this.api.resourceOn(this.rid, events, handler);
×
288
        return this;
×
289
    }
×
290

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

12✔
296
    /** Get the values of this collection as an array. */
12✔
297
    toArray(): Array<V> {
12✔
298
        return Array.from(this._list);
×
299
    }
×
300

12✔
301
    toJSON(): Array<unknown> {
12✔
302
        return this._list.map(v => (
×
303
            v !== null && typeof v === "object" && "toJSON" in v
×
304
                ? (v as { toJSON(): AnyObject; }).toJSON()
×
305
                : v
×
306
        ));
×
307
    }
×
308
}
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