-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathredux_like_observer.py
More file actions
44 lines (31 loc) · 1.15 KB
/
Copy pathredux_like_observer.py
File metadata and controls
44 lines (31 loc) · 1.15 KB
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
import copy
class Store(object):
def __init__(self, state):
self.state = state
def dispatch(self, action):
self.state = self.reducer(action)
def reducer(self, action):
state = copy.deepcopy(self.state)
if action['type'] == 'increment':
state['value'] = increment(state['value'])
elif action['type'] == 'decrement':
state['value'] = decrement(state['value'])
elif action['type'] == 'increment_by_amount':
state['value'] = increment_by_amount(state['value'], action['payload'])
else:
raise ValueError('Unknown action type')
return state
def increment(value):
return value + 1
def decrement(value):
return value - 1
def increment_by_amount(value, amount):
return value + amount
if __name__ == '__main__':
store = Store({'value': 0})
store.dispatch({'type': 'increment'})
print(store.state) # Output: {'value': 1}
store.dispatch({'type': 'decrement'})
print(store.state) # Output: {'value': 0}
store.dispatch({'type': 'increment_by_amount', 'payload': 5})
print(store.state) # Output: {'value': 5}