Skip to content

Instantly share code, notes, and snippets.

@crazy4groovy
Created September 22, 2023 17:00
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 crazy4groovy/ffdab20e23e2932c87057959f64aa355 to your computer and use it in GitHub Desktop.
Save crazy4groovy/ffdab20e23e2932c87057959f64aa355 to your computer and use it in GitHub Desktop.
// Create store accepts reducers map and initial state
function* createStore(reducers, initialState = {}) {
// Initialize state
let state = initialState;
// Extract the reducer keys upfront
const reducerKeys = Object.keys(reducers);
// Combine all reducers into one reducing function
const combinedReducer = (state, action) => {
return reducerKeys.reduce((newState, key) => {
// Pass slice of state into corresponding reducer
newState[key] = reducers[key](state[key], action);
return newState;
}, {});
}
// Generator loop handles each action
while (true) {
// Yield current state and wait for next action
const action = yield state;
// Pass current state and action to combined reducer
if (action) state = combinedReducer(state, action);
}
}
// Reducer example
function usersReducer(state = {}, action) {
// Reducer logic to update state immutably
// based on action.type
}
// Create reducers map with slice reducers
const reducers = {
users: usersReducer
};
// Initialize store with reducers (and optional initial state)
const store = createStore(reducers);
// Dispatch actions to trigger state updates, get value
store.next({type: 'ADD_USER'}).value;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment