From 2faf44af7443b3f858e15d63295a490afba83b4e Mon Sep 17 00:00:00 2001 From: Shin'ya Ueoka Date: Sun, 8 Oct 2017 15:11:09 +0900 Subject: move store to shared --- src/shared/store/index.js | 53 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 src/shared/store/index.js (limited to 'src/shared/store/index.js') diff --git a/src/shared/store/index.js b/src/shared/store/index.js new file mode 100644 index 0000000..2fafdf1 --- /dev/null +++ b/src/shared/store/index.js @@ -0,0 +1,53 @@ +class Store { + constructor(reducer, catcher) { + this.reducer = reducer; + this.catcher = catcher; + this.subscribers = []; + try { + this.state = this.reducer(undefined, {}); + } catch (e) { + catcher(e); + } + } + + dispatch(action, sender) { + if (action instanceof Promise) { + action.then((a) => { + this.transitNext(a, sender); + }).catch((e) => { + this.catcher(e, sender); + }); + } else { + try { + this.transitNext(action, sender); + } catch (e) { + this.catcher(e, sender); + } + } + return action; + } + + getState() { + return this.state; + } + + subscribe(callback) { + this.subscribers.push(callback); + } + + transitNext(action, sender) { + let newState = this.reducer(this.state, action); + if (JSON.stringify(this.state) !== JSON.stringify(newState)) { + this.state = newState; + this.subscribers.forEach(f => f(sender)); + } + } +} + +const empty = () => {}; + +const createStore = (reducer, catcher = empty) => { + return new Store(reducer, catcher); +}; + +export { createStore }; -- cgit v1.2.3