aboutsummaryrefslogtreecommitdiff
path: root/src/store/index.js
blob: 2d082964138b966aedc4533179330e924f537254 (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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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 = () => {};

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