45 lines
972 B
TypeScript
45 lines
972 B
TypeScript
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
|
|
|
|
export const LOAD = 'LOAD';
|
|
export const ADD = 'ADD';
|
|
export const EDIT = 'EDIT';
|
|
export const REMOVE = 'REMOVE';
|
|
|
|
|
|
type Id = string | number;
|
|
|
|
interface Identifiable {
|
|
_id?: Id;
|
|
}
|
|
|
|
export class Store<T extends Identifiable> {
|
|
items_ = [];
|
|
items$ = new BehaviorSubject<T[]>([]);
|
|
|
|
dispatch(action) {
|
|
this.items_ = this._reduce(this.items_, action);
|
|
this.items$.next(this.items_);
|
|
}
|
|
|
|
_reduce(items: T[], action) {
|
|
switch (action.type) {
|
|
case LOAD:
|
|
return [...action.data];
|
|
case ADD:
|
|
return [...items, action.data];
|
|
case EDIT:
|
|
return items.map(item => {
|
|
const editedItem = action.data;
|
|
if (item._id !== editedItem._id) {
|
|
return item;
|
|
}
|
|
return editedItem;
|
|
});
|
|
case REMOVE:
|
|
return items.filter(item => item._id !== action.data._id);
|
|
default:
|
|
return items;
|
|
}
|
|
}
|
|
}
|