Skip to content

Instantly share code, notes, and snippets.

@davidbgk
Last active March 3, 2016 20:37
Show Gist options
  • Save davidbgk/b028cc00cc9963af8161 to your computer and use it in GitHub Desktop.
Save davidbgk/b028cc00cc9963af8161 to your computer and use it in GitHub Desktop.
Playing with Redux concepts
const createStore = (reducer, state = reducer(undefined, {})) => {
const subscribers = new Set()
return {
dispatch: (action) => {
state = reducer(state, action)
subscribers.forEach(func => func(action))
},
subscribe: (func) => {
subscribers.add(func)
return () => subscribers.delete(func)
},
getState: () => state
}
}
const createReducer = (initialState, handlers) => {
return (state = initialState, action) => {
if (handlers.hasOwnProperty(action.type)) {
return handlers[action.type](state, action)
} else {
return state
}
}
}
const createAction = (type, ...argNames) => {
return (...args) => {
let action = { type }
argNames.forEach((arg, index) => {
action[argNames[index]] = args[index]
})
return action
}
}
const counter = createReducer({ counter: 0 }, {
['INCREMENT'](state, action) {
return { counter: state.counter + 1 }
},
['DECREMENT'](state, action) {
return { counter: state.counter - 1 }
}
})
const shoppingList = createReducer([], {
['ADD_ITEM'](state, action) {
return [ ...state, action.item ]
}
})
const store = createStore((state = {}, action) => {
return {
counter: counter(state.counter, action),
shoppingList: shoppingList(state.shoppingList, action)
}
})
const increment = createAction('INCREMENT')
const decrement = createAction('DECREMENT')
const addItem = createAction('ADD_ITEM', 'item')
console.log('begin:', store.getState())
const unsubscribe = store.subscribe((action) =>
console.log(store.getState(), action))
store.dispatch(increment())
store.dispatch(increment())
store.dispatch(decrement())
store.dispatch(increment())
store.dispatch(addItem('Apples'))
store.dispatch(addItem('Oranges'))
unsubscribe()
store.dispatch(decrement()) // => No log, manual.
console.log('end:', store.getState())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment