Skip to content

Instantly share code, notes, and snippets.

@conorhastings
Last active June 11, 2021 01:36
Show Gist options
  • Save conorhastings/ba8a06ce061466ac3fe7 to your computer and use it in GitHub Desktop.
Save conorhastings/ba8a06ce061466ac3fe7 to your computer and use it in GitHub Desktop.
A very (read: don't do this) simple implementation of redux
/*
* The reason for this is just a thought exercise
* often people(myself super included) are so confused
* when trying something new, but breaking it down
* to it's simplest existence can be the best way to understand
*/
function createStore(reducer, initState) {
let state = initState;
let subscribers = [];
const getState = () => state;
const dispatch = action => {
state = reducer(state, action);
subscribers.forEach((subscriber) => subscriber());
return action;
}
const subscribe = (listener) => {
subscribers.push(listener);
return () => {
subscribers = subscribers.slice(subscribers.indexOf(listener) + 1, 1);
};
}
return {
dispatch,
subscribe,
getState
}
}
const initState = {
name: "Conor",
redux: "awesome"
};
const myReducer = (state, action) => {
let newState = Object.assign({}, state);
switch (action.type) {
case "CHANGE_NAME":
newState.name = action.name;
break;
case "CHANGE_REDUX_ADJECTIVE":
newState.redux = action.adjective;
break;
default:
//do nothing
}
return newState
};
const store = createStore(myReducer, initState);
console.log(store.getState(), "initial state");
const subscriber = store.subscribe(() => {
console.log("i'll console state changes twice then unsubscribe so you will not be notified of the third dispatch", store.getState());
});
store.dispatch({
type: "CHANGE_NAME",
name: "Conor Hastings"
});
store.dispatch({
type: "CHANGE_REDUX_ADJECTIVE",
adjective: "great"
});
subscriber();
store.dispatch({
type: "CHANGE_NAME",
name: "Conor Cool Guy"
});
console.log("the state changed but since we unsubscribed the listener above was not notified o the final dispatch", store.getState());
@matef
Copy link

matef commented Apr 13, 2016

+1

@nagyadam2092
Copy link

+10

@leye0
Copy link

leye0 commented Jul 10, 2018

+100

@dieillusion
Copy link

thx!

@BenMakesGames
Copy link

BenMakesGames commented Mar 17, 2019

+Math.pow(10, currentYear - 2016);

@nandwana92
Copy link

I think this is buggy, https://gist.github.com/conorhastings/ba8a06ce061466ac3fe7#file-simple-redux-js-L20.
That statement will always return an empty array if I am not mistaken.

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