Last active
June 23, 2016 22:28
-
-
Save ffigiel/d4573ed9d402798d52eb0a46917859c6 to your computer and use it in GitHub Desktop.
redux-no-bs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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) | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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