6
6
StoreEnhancer ,
7
7
Dispatch ,
8
8
Observer ,
9
- ExtendState
9
+ ExtendState ,
10
+ ListenerCallback
10
11
} from './types/store'
11
12
import { Action } from './types/actions'
12
13
import { Reducer } from './types/reducers'
@@ -119,8 +120,9 @@ export function createStore<S, A extends Action, Ext = {}, StateExt = never>(
119
120
120
121
let currentReducer = reducer
121
122
let currentState = preloadedState as S
122
- let currentListeners : ( ( ) => void ) [ ] | null = [ ]
123
+ let currentListeners : Map < number , ListenerCallback > | null = new Map ( )
123
124
let nextListeners = currentListeners
125
+ let listenerIdCounter = 0
124
126
let isDispatching = false
125
127
126
128
/**
@@ -132,7 +134,10 @@ export function createStore<S, A extends Action, Ext = {}, StateExt = never>(
132
134
*/
133
135
function ensureCanMutateNextListeners ( ) {
134
136
if ( nextListeners === currentListeners ) {
135
- nextListeners = currentListeners . slice ( )
137
+ nextListeners = new Map ( )
138
+ currentListeners . forEach ( ( listener , key ) => {
139
+ nextListeners . set ( key , listener )
140
+ } )
136
141
}
137
142
}
138
143
@@ -197,7 +202,8 @@ export function createStore<S, A extends Action, Ext = {}, StateExt = never>(
197
202
let isSubscribed = true
198
203
199
204
ensureCanMutateNextListeners ( )
200
- nextListeners . push ( listener )
205
+ const listenerId = listenerIdCounter ++
206
+ nextListeners . set ( listenerId , listener )
201
207
202
208
return function unsubscribe ( ) {
203
209
if ( ! isSubscribed ) {
@@ -214,8 +220,7 @@ export function createStore<S, A extends Action, Ext = {}, StateExt = never>(
214
220
isSubscribed = false
215
221
216
222
ensureCanMutateNextListeners ( )
217
- const index = nextListeners . indexOf ( listener )
218
- nextListeners . splice ( index , 1 )
223
+ nextListeners . delete ( listenerId )
219
224
currentListeners = null
220
225
}
221
226
}
@@ -272,11 +277,9 @@ export function createStore<S, A extends Action, Ext = {}, StateExt = never>(
272
277
}
273
278
274
279
const listeners = ( currentListeners = nextListeners )
275
- for ( let i = 0 ; i < listeners . length ; i ++ ) {
276
- const listener = listeners [ i ]
280
+ listeners . forEach ( listener => {
277
281
listener ( )
278
- }
279
-
282
+ } )
280
283
return action
281
284
}
282
285
0 commit comments