Skip to content

Instantly share code, notes, and snippets.

@sag1v
Created March 31, 2019 17:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sag1v/623188c00455e060176f7dfd61976aa2 to your computer and use it in GitHub Desktop.
Save sag1v/623188c00455e060176f7dfd61976aa2 to your computer and use it in GitHub Desktop.
function createStore(reducer, initialState) {
var currentReducer = reducer;
var currentState = initialState;
var listeners = [];
var isDispatching = false;
function getState() {
return currentState;
}
function subscribe(listener) {
listeners.push(listener);
return function unsubscribe() {
var index = listeners.indexOf(listener);
listeners.splice(index, 1);
};
}
function dispatch(action) {
if (isDispatching) {
throw new Error('Reducers may not dispatch actions.');
}
try {
isDispatching = true;
currentState = currentReducer(currentState, action);
} finally {
isDispatching = false;
}
//listeners.slice().forEach(listener => listener());
listeners.forEach(listener => {
// this will prevent listeners to run to completion
//if prev listener unsubscribes the next listener
listener();
});
return action;
}
dispatch({
type: '@@redux/INIT'
});
return {
dispatch,
subscribe,
getState
};
}
const counter = (state = 0, action) => {
if (action.type === 'inc') {
return state + 1;
} else {
return state;
}
}
const store = createStore(counter);
unsubscribe1 = store.subscribe(() => {
console.log('listener 1');
const currentState = store.getState();
if (currentState === 2) {
unsubscribe2();
}
})
const unsubscribe2 = store.subscribe(() => console.log('listener 2'));
store.dispatch({
type: 'inc'
});
store.dispatch({
type: 'inc'
});
// if we remove .slice when running listeners.forEach we should get in console
// listener 1
// listener 2
// listener 1
// if we use .slice though, we will get
// listener 1
// listener 2
// listener 1
// listener 2
// meaning .slice will let the listeners run to completion
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment