Skip to content

Instantly share code, notes, and snippets.

@ibare
Created September 3, 2020 13:56
Show Gist options
  • Save ibare/1ed63de0c09c94a7ac79713d57b80f8d to your computer and use it in GitHub Desktop.
Save ibare/1ed63de0c09c94a7ac79713d57b80f8d to your computer and use it in GitHub Desktop.
import { createStore, actionCreator } from "./tiny-redux";
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 store = createStore(reducer);
store.subscribe(() => {
console.log(store.getState());
});
store.dispatch({
type: "init",
payload: {
count: 1
}
});
store.dispatch({
type: "inc"
});
store.dispatch(actionCreator("reset"));
const Increment = () => store.dispatch(actionCreator("inc"));
Increment();
Increment();
Increment();
export function createStore(reducer) {
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 });
return {
dispatch,
getState,
subscribe
};
}
export const actionCreator = (type, payload = {}) => ({
type,
payload: { ...payload }
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment