/
core-flux.js
114 lines (96 loc) · 2.45 KB
/
core-flux.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
/**
* Store dictionary
*/
const Stores = new Map()
/**
* Store ID value
*/
let idValue = 0
function getTypeTag(value) {
return Object.prototype.toString.call(value).slice(8, -1).toLowerCase()
}
function isPlainObject(value) {
return getTypeTag(value) === "object"
}
function throwError(msg) {
throw new Error(`[core-flux] ${msg}`)
}
/**
* Generate a new ID by incrementing the Store ID.
*/
function createId() {
return idValue + 1
}
function setInitialStore(id, initialState) {
Stores.set(id, {
state: initialState,
subscriptions: [],
})
}
/**
* Get a new deep clone of state from a store.
* @returns {Object}
*/
function getState(id) {
return Stores.get(id).state
}
/**
* Set a new state value to a store.
*/
function setState(id, rawNextStateValue) {
if (!isPlainObject(rawNextStateValue)) {
return throwError(
"bindState callback: The reduced state value must be a plain object. If there is no change in state, simply return it."
)
}
const store = Stores.get(id)
if (!store) return
const { state, subscriptions } = store
const newState = { ...state, ...rawNextStateValue }
Stores.set(id, {
state: newState,
subscriptions,
})
}
/**
* Creates a new store, then returns dispatch, subscribe, and pointer references.
*
* @param {Object} initialState
* @param {Function} reducer
* @param {Function} bindSubscriber
* @param {Function} bindState
* @returns {{dispatch: Function, subscribe: Function}}
*/
export function createStore(initialState, reducer, bindSubscriber, bindState) {
if (!initialState || !isPlainObject(initialState)) {
return throwError(
"createStore(): The initial state value must be a plain object."
)
}
const id = createId()
setInitialStore(id, initialState)
return {
dispatch(type, payload) {
const state = getState(id)
const reducedState = reducer(state, { type, payload })
return bindState(
Stores.get(id).subscriptions,
reducedState,
function (rawNextState) {
return setState(id, rawNextState)
}
)
},
subscribe(subscriber, data) {
if (!subscriber || !data) {
return throwError(
"subscribe(): `subscriber` and `data` arguments are required."
)
}
const { subscriptions, state } = Stores.get(id)
subscriptions.push([subscriber, data])
bindSubscriber(subscriptions[subscriptions.length - 1], state)
},
__data: Stores.get(id),
}
}