Created
September 22, 2023 17:00
-
-
Save crazy4groovy/ffdab20e23e2932c87057959f64aa355 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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