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

WolferyScripting / resclient-ts / #57

03 Sep 2025 01:24PM UTC coverage: 48.309% (-0.09%) from 48.394%
#57

push

DonovanDMC
1.1.15

230 of 292 branches covered (78.77%)

Branch coverage included in aggregate %.

1670 of 3641 relevant lines covered (45.87%)

9.84 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 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>>> implements Iterable<V> {
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
    /** Prevent this model from being unsubscribed. */
12✔
197
    keep(): void {
12✔
198
        this.cacheItem.keep();
×
199
    }
×
200

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

×
219
        return iterator.slice(-amount);
×
220
    }
×
221

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

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

12✔
235
    on<K extends keyof ModelEvents>(event: K, handler: (...args: ModelEvents[K]) => void): this;
12✔
236
    on(events: string | Array<string> | null, handler: AnyFunction): this;
12✔
237
    on(events: string | Array<string> | null, handler: AnyFunction): this {
12✔
238
        this.api.eventBus.on(this, events, handler);
×
239
        return this;
×
240
    }
×
241

12✔
242
    /**
12✔
243
     * Pick a random element from the collection, or undefined if the collection is empty.
12✔
244
     */
12✔
245
    random(): V | undefined {
12✔
246
        if (this.empty) {
×
247
            return undefined;
×
248
        }
×
249
        const iterable = Array.from(this._list);
×
250

×
251
        return iterable[Math.floor(Math.random() * iterable.length)];
×
252
    }
×
253

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

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

12✔
270
    remove(index: number): V | undefined {
12✔
271
        const item = this._list[index];
2✔
272
        if (item !== undefined) {
2✔
273
            this._list.splice(index, 1);
2✔
274

2✔
275
            if (this._idCallback) {
2✔
276
                delete this._map![this._idCallback(item)];
1✔
277
            }
1✔
278
        }
2✔
279

2✔
280
        return item;
2✔
281
    }
2✔
282

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

12✔
290
    resourceOn<K extends keyof ResourceEvents>(event: K, handler: (...args: ResourceEvents[K]) => void): this;
12✔
291
    resourceOn(events: string | Array<string> | null, handler: AnyFunction): this;
12✔
292
    resourceOn(events: string | Array<string> | null, handler: AnyFunction): this {
12✔
293
        this.api.resourceOn(this.rid, events, handler);
×
294
        return this;
×
295
    }
×
296

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

12✔
302
    /** Get the values of this collection as an array. */
12✔
303
    toArray(): Array<V> {
12✔
304
        return Array.from(this._list);
×
305
    }
×
306

12✔
307
    toJSON(): Array<unknown> {
12✔
308
        return this._list.map(v => (
×
309
            v !== null && typeof v === "object" && "toJSON" in v
×
310
                ? (v as { toJSON(): AnyObject; }).toJSON()
×
311
                : v
×
312
        ));
×
313
    }
×
314

12✔
315
    /** Undo preventing this model from being unsubscribed. */
12✔
316
    unkeep(): void {
12✔
317
        this.cacheItem.unkeep();
×
318
    }
×
319
}
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