Skip to content

Commit

Permalink
feat(ch10): implement a redux reducer
Browse files Browse the repository at this point in the history
  • Loading branch information
poulzinho committed Jan 25, 2020
1 parent 7f9e930 commit 5d3bae7
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
import {expect} from 'chai';
import {add, addN, compose, composeRight, filterRed, map, mapRedu, pipe} from "./10.1_abstraction_and_composition";
import {
add,
ADD_VALUE, addingReducer,
addN,
compose,
composeRight,
filterRed,
map,
mapRedu,
pipe
} from "./10.1_abstraction_and_composition";

describe("Abstraction and Composition", () => {
it("should fix a parameter in a function", () => {
Expand Down Expand Up @@ -76,6 +86,16 @@ describe("Abstraction and Composition", () => {
const pipedFn = pipe(add1, add5, multiplyWith3);

expect(pipedFn(5)).to.equal(33);
});

it("should implement a redux reducer", () => {
const actions = [
{type: ADD_VALUE, payload: {value: 1}},
{type: ADD_VALUE, payload: {value: 1}},
{type: ADD_VALUE, payload: {value: 1}},
];

expect(actions.reduce(addingReducer, 0)).to.equal(3);
})

});
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,15 @@ export const compose = (...fns) => x => fns.reduceRight((y, f) => f(y), x);
export const composeRight = (...fns) => x => fns.reverse().reduce((y, f) => f(y), x);

export const pipe = (...fns) => x => fns.reduce((y, f) => f(y), x);

export const ADD_VALUE = 'ADD_VALUE';
export const addingReducer = (state = 0, action = {}) => {
const {type, payload} = action;

switch (type) {
case ADD_VALUE:
return state + payload.value;
default:
return state;
}
};
12 changes: 12 additions & 0 deletions src/ch-10_abstraction-and-composition/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,15 @@ Good abstractions are:
## Reduce
- Fold
- Accumulate

## Redux reducer
- Library/architecture
- To manage app state
- Takes current state -> add action object -> returns new state

### Rules
- Reducer with no params returns initial state
- Reducer not handling action type returns state
- Reducers must be pure functions


0 comments on commit 5d3bae7

Please sign in to comment.