Skip to content

Instantly share code, notes, and snippets.

@ibare
Last active July 4, 2023 15:36
Show Gist options
  • Save ibare/0eb8597551070bf1ebf8e797439913a3 to your computer and use it in GitHub Desktop.
Save ibare/0eb8597551070bf1ebf8e797439913a3 to your computer and use it in GitHub Desktop.
Tiny Redux
import { createStore, actionCreator } from "./redux-middleware";
function reducer(state = {}, { type, payload }) {
switch (type) {
case "init":
return {
...state,
count: payload.count
};
case "inc":
return {
...state,
count: state.count + 1
};
case "reset":
return {
...state,
count: 0
};
default:
return { ...state };
}
}
const logger = (store) => (next) => (action) => {
console.log("logger: ", action.type);
next(action);
};
const monitor = (store) => (next) => (action) => {
setTimeout(() => {
console.log("monitor: ", action.type);
next(action);
}, 2000);
};
const store = createStore(reducer, [logger, monitor]);
store.subscribe(() => {
console.log(store.getState());
});
store.dispatch({
type: "init",
payload: {
count: 1
}
});
store.dispatch({
type: "inc"
});
const Reset = () => store.dispatch(actionCreator("reset"));
const Increment = () => store.dispatch(actionCreator("inc"));
Increment();
Reset();
Increment();
export function createStore(reducer, middlewares = []) {
let state;
const listeners = [];
const publish = () => {
listeners.forEach(({ subscriber, context }) => {
subscriber.call(context);
});
};
const dispatch = (action) => {
state = reducer(state, action);
publish();
};
const subscribe = (subscriber, context = null) => {
listeners.push({
subscriber,
context
});
};
const getState = () => ({ ...state });
const store = {
dispatch,
getState,
subscribe
};
middlewares = Array.from(middlewares).reverse();
let lastDispatch = store.dispatch;
middlewares.forEach((middleware) => {
lastDispatch = middleware(store)(lastDispatch);
});
return { ...store, dispatch: lastDispatch };
}
export const actionCreator = (type, payload = {}) => ({
type,
payload: { ...payload }
});
@doyoung0205
Copy link

디버깅 setting 은 어떻게 만드나요??

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment