UNPKG

amocrm-client

Version:
110 lines (83 loc) 3.3 kB
import { IResourceCollection } from "../interfaces/api"; export class ResourceCollection<T> implements IResourceCollection<T> { data: T[]; constructor(data?: T[]) { this.data = data || []; } get(id: number): T | undefined { return this.data.find((element) => (element as any).hasOwnProperty('id') && (element as any).id === id); } map<U>(callbackfn: (value: T, index: number, array: T[]) => U): ResourceCollection<U> { return new ResourceCollection(this.data.map(callbackfn)); } filter(callbackfn: (value: T, index: number, array: T[]) => boolean): ResourceCollection<T> { return new ResourceCollection(this.data.filter(callbackfn)); } reduce<U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U { return this.data.reduce(callbackfn, initialValue); } find(callbackfn: (value: T, index: number, array: T[]) => boolean): T | undefined { return this.data.find(callbackfn); } findWhere(props: { [K in keyof T]?: T[K] }): T | undefined { return this.data.find((element) => { return Object.entries(props).every(([key, value]) => { return element[key as keyof T] === value; }); }); } where(props: { [K in keyof T]?: T[K] }): ResourceCollection<T> { return this.filter((element) => { return Object.entries(props).every(([key, value]) => { return element[key as keyof T] === value; }); }); } every(callbackfn: (value: T, index: number, array: T[]) => boolean): boolean { return this.data.every(callbackfn); } some(callbackfn: (value: T, index: number, array: T[]) => boolean): boolean { return this.data.some(callbackfn); } each(callbackfn: (value: T, index: number, array: T[]) => void): void { this.data.forEach(callbackfn); } chunk(size: number): IResourceCollection<T[]> { const chunks = []; for (let i = 0, j = this.data.length; i < j; i += size) { chunks.push(this.data.slice(i, i + size)); } return new ResourceCollection(chunks); } add(models: T[] | ResourceCollection<T>): void { if (models instanceof ResourceCollection) { this.data.push(...models.data); } else { this.data.push(...models); } } push(model: T) { this.data.push(model); } pluck<K extends keyof T>(key: K): any[] { return this.data.map((model) => model[key]); } sort(compareFn?: (a: T, b: T) => number): IResourceCollection<T> { return new ResourceCollection(this.data.sort(compareFn)); } sortBy<K extends keyof T>(key: K): IResourceCollection<T> { return new ResourceCollection(this.data.sort((a, b) => (a[key] > b[key] ? 1 : -1))); } first(): T | undefined { return this.data[0]; } last(): T | undefined { return this.data[this.data.length - 1]; } all(): T[] { return this.data; } size(): number { return this.data.length; } }