Hard
This question is a daily question and will count towards your daily streak.
You're developing a custom state management solution for a complex web application. The system needs to track state changes and allow for time-travel debugging. What will be the final state after executing the following code?
1class StateManager {2 #states = [];3 #subscribers = new Set();4 #currentIndex = -1;56 dispatch(action) {7 const newState = this.#reducer(this.currentState, action);8 this.#states = this.#states.slice(0, this.#currentIndex + 1);9 this.#states.push(newState);10 this.#currentIndex++;11 this.#notifySubscribers();12 }1314 #reducer(state = { count: 0, history: [] }, action) {15 switch (action.type) {16 case 'INCREMENT':17 return {18 count: state.count + action.payload,19 history: [...state.history, `Added ${action.payload}`]20 };21 case 'DECREMENT':22 return {23 count: state.count - action.payload,24 history: [...state.history, `Subtracted ${action.payload}`]25 };26 case 'RESET':27 return {28 count: 0,29 history: [...state.history, 'Reset']30 };31 default:32 return state;33 }34 }3536 get currentState() {37 return this.#currentIndex >= 038 ? this.#states[this.#currentIndex]39 : this.#reducer(undefined, {});40 }4142 timeTravel(index) {43 if (index >= 0 && index < this.#states.length) {44 this.#currentIndex = index;45 this.#notifySubscribers();46 }47 }4849 #notifySubscribers() {50 this.#subscribers.forEach(subscriber => subscriber(this.currentState));51 }52}5354const manager = new StateManager();55manager.dispatch({ type: 'INCREMENT', payload: 5 });56manager.dispatch({ type: 'DECREMENT', payload: 2 });57manager.dispatch({ type: 'INCREMENT', payload: 3 });58manager.timeTravel(1);59manager.dispatch({ type: 'RESET' });60console.log(manager.currentState);