-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
48 lines (38 loc) · 997 Bytes
/
index.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
function and(update, state, react) {
return (...actions) => {
if (actions.length > 0) {
const action = actions.shift()
if (typeof action !== "function") {
throw new TypeError(action + " is not a function")
}
const apply = (fn, ...args) => {
if (args.length + actions.length > 0) {
fn(update, state, react)(...args, ...actions)
}
}
let result = action({state: state()})
if (typeof result == "function") {
result({apply: (fn) => apply(and, fn)})
return
}
if (result instanceof Error === true) {
return
}
update(result)
react(state())
if (actions.length > 0) {
return and(update, state, react)(...actions)
}
}
}
}
function init(value) {
let state = value
const subscribers = []
return {
apply: (fn) => and(newState => state = newState, () => state, state => subscribers.forEach(fn => fn(state)), {})(fn),
subscribe: f => subscribers.push(f),
getState: () => state
}
}
module.exports = { init, and };