make _all$ protected in entities service

This commit is contained in:
Dan Percic 2022-08-16 19:14:48 +03:00
parent b42baa37fc
commit 894405be8a
2 changed files with 27 additions and 6 deletions

View File

@ -22,17 +22,17 @@ export class EntitiesService<
protected readonly _entityClass?: new (entityInterface: Interface, ...args: unknown[]) => Class;
protected readonly _entityChanged$ = new Subject<Class>();
protected readonly _entityDeleted$ = new Subject<Class>();
readonly #all$ = new BehaviorSubject<Class[]>([]);
protected readonly _all$ = new BehaviorSubject<Class[]>([]);
constructor() {
super();
this.all$ = this.#all$.asObservable().pipe(shareDistinctLast());
this.allLength$ = this.#all$.pipe(getLength, shareDistinctLast());
this.all$ = this._all$.asObservable().pipe(shareDistinctLast());
this.allLength$ = this._all$.pipe(getLength, shareDistinctLast());
this.noData$ = this.#noData$;
}
get all(): Class[] {
return Object.values(this.#all$.getValue());
return Object.values(this._all$.getValue());
}
get #noData$(): Observable<boolean> {
@ -78,7 +78,7 @@ export class EntitiesService<
return entity;
});
this.#all$.next(newEntities);
this._all$.next(newEntities);
// Emit observables only after entities have been updated
@ -94,7 +94,7 @@ export class EntitiesService<
remove(id: Id) {
const entity = this.all.find(item => item.id === id);
if (entity) {
this.#all$.next(this.all.filter(item => item.id !== id));
this._all$.next(this.all.filter(item => item.id !== id));
this._entityDeleted$.next(entity);
}
}

View File

@ -137,6 +137,21 @@ export function bool(value: unknown): boolean {
return Boolean(_value);
}
export function groupBy<T, Q>(array: T[], predicate: (value: T, index: number, items: T[]) => Q) {
return array.reduce((dict, value, index, items) => {
const key = predicate(value, index, items);
if (dict.has(key)) {
const group = dict.get(key);
if (!group) {
throw new Error(`Oh, why, group ${key} is undefined`);
}
group.push(value);
return dict;
}
return dict.set(key, [value]);
}, new Map<Q, T[]>());
}
declare global {
interface String {
capitalize(): string;
@ -150,6 +165,8 @@ declare global {
* The value returned from the function determines whether the element is kept or removed.
*/
filterTruthy(and?: (value: T) => boolean): T[];
groupBy<Key>(condition: (value: T) => Key): Map<Key, T[]>;
}
interface Console {
@ -172,6 +189,10 @@ Array.prototype.filterTruthy = function <T>(this: T[], predicate: (value: T) =>
return this.filter(value => !!value && predicate(value));
};
Array.prototype.groupBy = function <T, Key>(this: T[], condition: (value: T) => Key): Map<Key, T[]> {
return groupBy(this, condition);
};
/**
* Use this in field initialization or in constructor of a service / component
* @param param