-
Notifications
You must be signed in to change notification settings - Fork 172
Expand file tree
/
Copy pathreducer.ts
More file actions
60 lines (52 loc) · 1.56 KB
/
reducer.ts
File metadata and controls
60 lines (52 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import { handleActions, Action } from 'redux-actions';
import { Todo, IState } from './model';
import {
ADD_TODO,
DELETE_TODO,
EDIT_TODO,
COMPLETE_TODO,
COMPLETE_ALL,
CLEAR_COMPLETED
} from './constants/ActionTypes';
const initialState: IState = [<Todo>{
text: 'Use Redux with TypeScript',
completed: false,
id: 0
}];
export default handleActions<IState, Todo>({
[ADD_TODO]: (state: IState, action: Action<Todo>): IState => {
return [{
id: state.reduce((maxId, todo) => Math.max(todo.id, maxId), -1) + 1,
completed: action.payload.completed,
text: action.payload.text
}, ...state];
},
[DELETE_TODO]: (state: IState, action: Action<Todo>): IState => {
return state.filter(todo =>
todo.id !== action.payload.id
);
},
[EDIT_TODO]: (state: IState, action: Action<Todo>): IState => {
return <IState>state.map(todo =>
todo.id === action.payload.id
? { ...todo, text: action.payload.text }
: todo
);
},
[COMPLETE_TODO]: (state: IState, action: Action<Todo>): IState => {
return <IState>state.map(todo =>
todo.id === action.payload.id ?
{ ...todo, completed: !todo.completed } :
todo
);
},
[COMPLETE_ALL]: (state: IState, action: Action<Todo>): IState => {
const areAllMarked = state.every(todo => todo.completed);
return <IState>state.map(todo => ({ ...todo,
completed: !areAllMarked
}));
},
[CLEAR_COMPLETED]: (state: IState, action: Action<Todo>): IState => {
return state.filter(todo => todo.completed === false);
}
}, initialState);