How would you implement createStore function from Redux?
@Yomesh Gupta

Redux is a very popular state management library and it is used as a de-facto standard in millions of projects out in the real world applications. Usage typical looks like the following

import { createStore } from 'redux';

const rootReducer = (state = {}, action) => {
  switch(action.type) {
    case 'ADD_USER':
      return {
        ...state,
        user: action.payload
      };
    default:
      return state;
  };
};

const initialState = {};

const store = createStore(rootReducer, initialState);

Demo:

Now, createStore returns an object that exposes many methods but we want you to focus on primarily three: getState, subscribe, and dispatch. Your problem statement is to create your copy of createStore that takes reducer and initialState as arguments and behaves exactly like createStore from redux.

import { createStore } from 'customRedux';

const rootReducer = (state = {}, action) => {
  switch(action.type) {
    case 'ADD_USER':
      return {
        ...state,
        user: action.payload
      };
    default:
      return state;
  };
};

const initialState = {};

const store = createStore(rootReducer, initialState);

store.subscribe(() => {
  console.log("Listener called");
});

console.log(store.getState()); // {}

store.dispatch({
  type: 'ADD_USER',
  payload: {
    id: 1,
    name: 'Yomesh Gupta'
  }
});

/**
  Listener called
   { user: { id: 1, name: 'Yomesh Gupta' } }
**/
console.log(store.getState());

You need to add the validations too.

Loading IDE...

https://www.devtools.tech/