-
Notifications
You must be signed in to change notification settings - Fork 60
/
state_handler.js
44 lines (38 loc) · 1.14 KB
/
state_handler.js
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 isEqual from 'fast-deep-equal'
const create_state_handler = () => {
const state = {}
let subscriptions = []
const update_state = (variable, value) => {
// Replace old state with new state, report if value has actually changed
const old_state = Object.assign({}, state)
state[variable] = value
if (isEqual(old_state, state)) return false
return true
}
const handle_change = (variable, value) => {
// Return early if state didn't actually change
if (!update_state(variable, value)) return
const old_subscriptions = subscriptions.slice()
subscriptions = []
old_subscriptions.map(callback => callback(state_handler, callback))
}
const state_handler = {
'get_state': () => state,
'reset': () => {
subscriptions = []
},
'init_variable': (variable, value) => {
if (state[variable] === undefined) {
handle_change(variable, value)
}
},
'set_variable': (variable, value) => {
handle_change(variable, value)
},
'subscribe': (callback) => {
subscriptions.push(callback)
}
}
return state_handler
}
export default create_state_handler