-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathreducer.js
More file actions
42 lines (35 loc) · 1.29 KB
/
Copy pathreducer.js
File metadata and controls
42 lines (35 loc) · 1.29 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
/*
Lien utile : https://www.youtube.com/watch?v=TOhUqDGNFtA
*/
const ACTIONS = {
INCREMENT: "increment",
DECREMENT: "decrement",
RESET: "reset",
};
/**
* @param { Object } state : l'état courrant
* @param {{type : string, payload : *}} action : action à appliquer. Contient un type et un contenu (payload)
* @returns { Object } le nouveau état modifié (ou non) par l'action
*/
const reducer = (state, action) => {
switch (action.type) {
case ACTIONS.INCREMENT:
return { name: state.name, count: state.count + action.payload };
case ACTIONS.DECREMENT:
return { name: state.name, count: state.count - action.payload };
case ACTIONS.RESET:
return { name: state.name, count: 0 };
default:
return state;
}
};
let counter = { name: "Timer", count: 0 };
const incrementAction = { type: ACTIONS.INCREMENT, payload: 1 };
counter = reducer(counter, incrementAction);
console.log(counter); // { name: 'Timer', count: 1}
counter = reducer(counter, { type: ACTIONS.INCREMENT, payload: 10 });
console.log(counter); // { name: 'Timer', count: 11}
counter = reducer(counter, { type: ACTIONS.DECREMENT, payload: 5 });
console.log(counter); // { name: 'Timer', count: 6}
counter = reducer(counter, { type: ACTIONS.RESET });
console.log(counter); // { name: 'Timer', count: 0}