Skip to content

Instantly share code, notes, and snippets.

@dSalieri
Last active November 20, 2022 05:36
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 dSalieri/8a0cf1632ed2db417aab1a4af7c2bbcc to your computer and use it in GitHub Desktop.
Save dSalieri/8a0cf1632ed2db417aab1a4af7c2bbcc to your computer and use it in GitHub Desktop.
Redux architecture

Этот документ предназначен для того чтобы понять как работает архитектура Redux, а именно так называемого хранилища. Здесь предоставлены различные функции для использования их в примерах Redux архитектуры.

Субстракт реализации вытащен из исходников .ts и переписан под .js. Так что это реальное представление Redux в ее основной сути.

Приятного разбора :)

/// createStore
function createStore(reducer, initialState, enhancer) {
if (typeof initialState === 'function') {
enhancer = initialState;
initialState = undefined;
}
if (typeof enhancer === 'function') {
return enhancer(createStore)(reducer, initialState);
}
let state = initialState;
return {
dispatch: (action) => {
state = reducer(state, action);
},
getState: () => state,
};
}
/// applyMiddleware
function applyMiddleware(...middlewares) {
return (createStore) => (reducer, initialState) => {
const store = createStore(reducer, initialState);
const middlewareAPI = {
getState: store.getState,
dispatch: (action) => dispatch(action),
};
const chain = middlewares.map((middleware) => middleware(middlewareAPI));
const dispatch = compose(...chain)(store.dispatch);
return {
...store,
dispatch,
};
};
}
/// compose
function compose(...functions) {
return functions.reduce(
(acc, val) =>
(...args) =>
acc(val(...args))
);
}
/// custom reducer if alone
function standaloneReducer(state = { value: 0 }, action) {
switch (action.type) {
case 'INCREMENT':
return { ...state, value: state.value + 1 };
case 'DECREMENT':
return { ...state, value: state.value - 1 };
default:
return state;
}
}
/// compostition global
function globalReducer(state = {}, action) {
return {
value: reducer(state.value, action),
};
}
/// custom reducer
function reducer(state = 0, action) {
switch (action.type) {
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
return state - 1;
default:
return state;
}
}
/// custom middleware
function helloLog(store) {
return (next) => (action) => {
console.log('hello');
next(action);
};
}
/// creation of store
var store = createStore(globalReducer, applyMiddleware(helloLog));
/// dispatching
store.dispatch({ type: 'INCREMENT' });
/// looking at result
store.getState(); /// {value: 1}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment