articles to articlesList and slice and length functions for ArticlesModel to act like an array
This commit is contained in:
@@ -36,11 +36,14 @@ export interface ArticleModel {
|
||||
}
|
||||
|
||||
export interface ArticlesModel {
|
||||
articles: ArticleModel[];
|
||||
articlesList: ArticleModel[];
|
||||
articlesById: Record<string, ArticleModel>;
|
||||
// articlesByTag: Record<string, ArticleModel[]>;
|
||||
// articlesByAuthor: Record<string, ArticleModel[]>;
|
||||
|
||||
length: number;
|
||||
slice(start: number, end?: number): ArticleModel[];
|
||||
|
||||
refresh(list: ArticleModel[]): ArticlesModel;
|
||||
create(a: ArticleModel): ArticlesModel;
|
||||
readByIndex(index: number): ArticleModel | undefined;
|
||||
@@ -50,13 +53,30 @@ export interface ArticlesModel {
|
||||
}
|
||||
|
||||
// ---------- FACTORY ----------
|
||||
export function createArticlesModelObject(): ArticlesModel {
|
||||
export function createArticlesModelObject(
|
||||
articles: ArticleModel[] = []
|
||||
): ArticlesModel {
|
||||
const initialMap: Record<string, ArticleModel> = {};
|
||||
for (const a of articles) {
|
||||
if (a._id) initialMap[a._id] = a;
|
||||
}
|
||||
|
||||
return {
|
||||
articles: [],
|
||||
articlesById: {},
|
||||
articlesList: articles,
|
||||
articlesById: initialMap,
|
||||
|
||||
// --- computed property ---
|
||||
get length() {
|
||||
return this.articlesList.length;
|
||||
},
|
||||
|
||||
// --- array-like slice ---
|
||||
slice(start: number, end?: number) {
|
||||
return this.articlesList.slice(start, end);
|
||||
},
|
||||
|
||||
refresh(list) {
|
||||
this.articles = list;
|
||||
this.articlesList = list;
|
||||
|
||||
const map: Record<string, ArticleModel> = {};
|
||||
for (const a of list) {
|
||||
@@ -67,13 +87,13 @@ export function createArticlesModelObject(): ArticlesModel {
|
||||
},
|
||||
|
||||
create(a) {
|
||||
this.articles = createInList(this.articles, a);
|
||||
this.articlesList = createInList(this.articlesList, a);
|
||||
this.articlesById = createById(this.articlesById, a);
|
||||
return this;
|
||||
},
|
||||
|
||||
readByIndex(index) {
|
||||
return readInList(this.articles, index);
|
||||
return readInList(this.articlesList, index);
|
||||
},
|
||||
|
||||
readById(id) {
|
||||
@@ -81,13 +101,13 @@ export function createArticlesModelObject(): ArticlesModel {
|
||||
},
|
||||
|
||||
update(a) {
|
||||
this.articles = updateInList(this.articles, a);
|
||||
this.articlesList = updateInList(this.articlesList, a);
|
||||
this.articlesById = updateById(this.articlesById, a);
|
||||
return this;
|
||||
},
|
||||
|
||||
delete(id) {
|
||||
this.articles = deleteInList(this.articles, id);
|
||||
this.articlesList = deleteInList(this.articlesList, id);
|
||||
this.articlesById = deleteById(this.articlesById, id);
|
||||
return this;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user