-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.js
90 lines (80 loc) · 1.7 KB
/
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
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
var inWindow = typeof window !== 'undefined'
var set = inWindow
? window.requestAnimationFrame
: setTimeout
var cancel = inWindow
? window.cancelAnimationFrame
: clearTimeout
var timeout
module.exports = function Redeux (initialState) {
var state = initialState || {}
var reducers = []
var listeners = []
var actions = []
function register () {
var args = arguments
var l = args.length
var i = 0
var r
var 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 () {
var action = actions.pop()
reduce(action)
if (actions.length) {
cancel(timeout)
timeout = set(dispatch)
} else {
notify()
}
}
function notify () {
var i = 0
var l = listeners.length
for (i; i < l; i++) {
listeners[i](state)
}
}
function queue (action) {
actions.push(action)
timeout = set(dispatch)
}
function reduce (action) {
var i = 0
var l = reducers.length
var r
var 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
}