Skip to content

Instantly share code, notes, and snippets.

@ffigiel
Last active June 23, 2016 22:28
Show Gist options
  • Save ffigiel/d4573ed9d402798d52eb0a46917859c6 to your computer and use it in GitHub Desktop.
Save ffigiel/d4573ed9d402798d52eb0a46917859c6 to your computer and use it in GitHub Desktop.
redux-no-bs
// in actionTypes.js
export const ADD = 'ADD'
// in actions.js
export const add = createAction(ADD)
export const addSquare = createAction(ADD, (x) => x * x)
// in reducers.js
export default createReducer(0, {
[ADD]: (state, payload) => state + payload,
})
// example
test(t => {
let state
state = reducer(1, add(42))
t.is(state, 43)
state = reducer(1, addSquare(3))
t.is(state, 10)
})
export function createAction(type, payloadCreator=identity) {
return function actionCreator(...args) {
return {
type,
payload: payloadCreator(...args)
}
}
}
export function createReducer(initialState, handlers) {
return function reducer(state=initialState, { type, payload }) {
const handler = handlers[type]
return (handler)
? handler(state, payload)
: state
}
}
function identity (x) {
return x
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment