-
Notifications
You must be signed in to change notification settings - Fork 6
/
redeux.mjs
82 lines (73 loc) · 1.59 KB
/
redeux.mjs
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
/* global window */
export default function Redeux (initialState) {
var state = initialState || {}
var reducers = []
var listeners = []
var actions = []
var timeout
function register () {
let args = arguments
let l = args.length
let i = 0
let r
let key
for (i; i < l; i++) {
r = args[i]
key = r.key || r.name
if (typeof r === 'function') {
state[key] = r(state[key])
reducers.push(r)
}
}
return reducers.length
}
function subscribe (listener) {
return typeof listener === 'function' &&
listeners.push(listener)
}
function unsubscribe (listener) {
return listeners.splice(listeners.indexOf(listener), 1)
}
function dispatch () {
reduce(actions.pop())
if (actions.length) {
window.cancelAnimationFrame(timeout)
timeout = window.requestAnimationFrame(dispatch)
} else {
notify()
}
}
function notify () {
let i = 0
let l = listeners.length
for (i; i < l; i++) {
listeners[i](state)
}
}
function queue (action) {
actions.push(action)
timeout = window.requestAnimationFrame(dispatch)
}
function reduce (action) {
let i = 0
let l = reducers.length
let r
let key
for (i; i < l; i++) {
r = reducers[i]
key = r.key || r.name
state[key] = r(state[key], action)
}
return state
}
function store (fn) {
return fn
? fn(reduce())
: reduce()
}
store.subscribe = subscribe
store.unsubscribe = unsubscribe
store.register = register
store.dispatch = queue
return store
}