Skip to content

Instantly share code, notes, and snippets.

@tomasr8
Created February 17, 2020 11:41
Show Gist options
  • Save tomasr8/a7d571858cc4b0b16afb0e2dd162f29e to your computer and use it in GitHub Desktop.
Save tomasr8/a7d571858cc4b0b16afb0e2dd162f29e to your computer and use it in GitHub Desktop.
Redux in 30 lines
function createStore(reducer) {
const store = {
state: {},
reducer,
dispatch(action) {
this.state = this.reducer(action, this.state)
}
}
store.dispatch({})
return store
}
function combineReducers(reducers) {
return (action, state) => {
const nextState = {}
for (const key of Object.keys(reducers)) {
nextState[key] = reducers[key](action, state[key])
}
return nextState
}
}
module.exports = {
createStore,
combineReducers
}
const { createStore, combineReducers } = require('./redux.js')
function countReducer(action, count = 0) {
switch(action.type) {
case 'INC':
count += 1
break;
default:
break;
}
return count
}
function helloReducer(action, greeting = 'Hello, John!') {
switch(action.type) {
case 'NAME':
greeting = `Hello, ${action.payload}!`
break;
default:
break;
}
return greeting
}
const reducer = combineReducers({ count: countReducer, hello: helloReducer })
const store = createStore(reducer)
console.log(store.state)
store.dispatch({ type: 'INC' })
console.log(store.state)
store.dispatch({ type: 'INC' })
console.log(store.state)
store.dispatch({ type: 'NAME', payload: 'Sam' })
console.log(store.state)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment