Skip to content

Instantly share code, notes, and snippets.

@intojs
Last active Mar 11, 2018
Embed
What would you like to do?
// @flow
import {update} from "ramda";
import type {Article} from "../domain/Article";
import type {ArticleState} from "./ArticleState";
export type ArticleStore = {
addArticle(article: Article): void;
removeArticle(article: Article): void;
updateArticle(article: Article): void;
subscribe(subscriber: Function): Function;
unsubscribe(subscriber: Function): void;
}
export const addArticle = (articleState: ArticleState, article: Article) => articleState.concat(article);
export const removeArticle = (articleState: ArticleState, article: Article) =>
articleState.filter((a: Article) => a.id !== article.id);
export const updateArticle = (articleState: ArticleState, article: Article) => {
const index = articleState.findIndex((a: Article) => a.id === article.id);
return update(index, article, articleState);
};
export const subscribe = (subscribers: Function[], subscriber: Function) =>
subscribers.concat(subscriber);
export const unsubscribe = (subscribers: Function[], subscriber: Function) =>
subscribers.filter((s: Function) => s !== subscriber);
export const notify = (articleState: ArticleState, subscribers: Function[]) =>
subscribers.forEach((s: Function) => s(articleState));
export const ArticleStoreFactory = (() => {
let articleState: ArticleState = Object.freeze([]);
let subscribers: Function[] = Object.freeze([]);
return {
addArticle: (article: Article) => {
articleState = addArticle(articleState, article);
notify(articleState, subscribers);
},
removeArticle: (article: Article) => {
articleState = removeArticle(articleState, article);
notify(articleState, subscribers);
},
updateArticle: (article: Article) => {
articleState = updateArticle(articleState, article);
notify(articleState, subscribers);
},
subscribe: (subscriber: Function) => {
subscribers = subscribe(subscribers, subscriber);
return subscriber;
},
unsubscribe: (subscriber: Function) => {
subscribers = unsubscribe(subscribers, subscriber);
}
}
});
export const articleStore = ArticleStoreFactory();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment