aboutsummaryrefslogtreecommitdiff
path: root/src/store/index.js
blob: bcb65d636176cf0c00180fc566a665d6315837a9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Store {
  constructor(reducer, catcher) {
    this.reducer = reducer;
    this.catcher = catcher;
    this.state = this.reducer(undefined, {});
  }

  dispatch(action) {
    if (action instanceof Promise) {
      action.then((a) => {
        this.state = this.reducer(this.state, a);
      }).catch(this.catcher)
    } else {
      try {
        this.state = this.reducer(this.state, action);
      } catch (e) {
        this.catcher(e);
      }
    }
  }
}

const empty = () => {};

export function createStore(reducer, catcher = empty) {
  return new Store(reducer, catcher);
}