-
Notifications
You must be signed in to change notification settings - Fork 0
/
dux.py
59 lines (48 loc) · 1.47 KB
/
dux.py
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
52
53
54
55
56
57
58
59
"""
basic implementation of a Redux-style store and combine_reducers function
"""
class Store:
def __init__(self, reducer):
"""
initializes a new store that will use the given reducer
"""
self._reducer = reducer
self._state = None
self._listeners = []
self.dispatch()
@property
def state(self):
"""
returns the stored state
"""
return self._state
def dispatch(self, action=None):
"""
dispatches the given action to trigger a state change then inform the
subscribed listeners
"""
if action is None:
action = {}
self._state = self._reducer(self._state, action)
for listener in self._listeners:
listener()
def subscribe(self, listener):
"""
subscribes the given listener and returns a no-arg callable which can
be called later to unsubscribe the listener
"""
self._listeners.append(listener)
def unsubscribe():
self._listeners.remove(listener)
return unsubscribe
def combine_reducers(reducers):
"""
takes a dict mapping state keys to the reducers responsible for them and
return a single reducer that will delegate appropriately
"""
def reducer(state, action):
return {
key: value(state.get(key) if state else None, action)
for key, value in reducers.items()
}
return reducer