На самом деле в коде было 2 ошибки и функция unsubscribe была не реализована.
const initialState = {
counter: 0
};
function createStore(reducer) {
let state = initialState;
let callbacks = [];
return {
getState() {
return state;
},
subscribe(propType, callback) {
callbacks.push(callback);
},
unsubscribe(fn) {
const index = callbacks.indexOf(fn);
if (index !== -1) {
callbacks.splice(index, 1);
console.log("Unsubscription");
} else {
throw new Error('Unsubscription error, callback function not found in store.')
}
},
dispatch(action) {
state = reducer(state, action);
callbacks.forEach((callback) => callback(state));
}
};
}
const reducer = (state = initialState, action) => {
switch (action.type) {
case "INCREMENT": {
return {
...state,
counter: state.counter + 1
};
}
default:
return state;
}
};
const store = createStore(reducer);
const fn = (state) => console.log("Counter has been changed", state.counter);
store.subscribe("counter", fn);
setInterval(() => store.dispatch({ type: "INCREMENT" }), 1000);
setTimeout(() => store.unsubscribe(fn), 3111);