/
index.js
120 lines (104 loc) · 2.38 KB
/
index.js
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
//The state Tree
function createStore(reducer){
let state;
let listeners = [];
const getState = ()=>state;
const subscribe = (listener) => {
listeners.push(listener);
return () => {
listeners = listeners.filter((l) => l !== listener);
}
};
const dispatch = (action) => {
state = reducer(state,action);
listeners.forEach((listeners) => listeners());
}
return {
getState,
subscribe,
dispatch
}
}
//App Code
const ADD_TODO = 'ADD_TODO';
const REMOVE_TODO = 'REMOVE_TODO';
const TOGGLE_TODO = 'TOGGLE_TODO';
const ADD_GOAL = 'ADD_GOAL';
const REMOVE_GOAL = 'REMOVE_GOAL';
function addTodoAction(todo) {
return {
type: ADD_TODO,
todo,
}
}
function removeTodoAction(id) {
return {
type: REMOVE_TODO,
todo,
}
}
function toggleTodoAction(id) {
return {
type: TOGGLE_TODO,
todo,
}
}
function addGoalAction(id) {
return {
type: ADD_GOAL,
todo,
}
}
function removeGoalAction(id) {
return {
type: REMOVE_GOAL,
todo,
}
}
//The reducer function - Passed as an arugument while initializing the store
function todos(state = [], action){
switch(action.type) {
case 'ADD_TODO':
return state.concat([action.todo]);
case 'REMOVE_TODO':
return state.filter((todo) => todo.id !== action.id);
case 'TOGGLE_TODO':
return state.map((todo) => todo.id !== action.id ? todo :
Object.assign({},todo, { complete: !todo.complete }));
default:
return state;
}
}
function goals(state = [], action){
switch(action.type) {
case 'ADD_GOAL':
return state.concat([action.goal]);
case 'REMOVE_GOAL':
return state.filter((goal) => goal.id !== action.id);
default :
return state;
}
}
function app(state ={}, action){
return {
todos: todos(state.todos, action),
goals: goals(state.goals, action)
}
}
const store = createStore(app);
const unsubscribe = store.subscribe(()=>{
console.log("State Changed!");
})
store.dispatch({
type:ADD_TODO,
todo: {
id: 0,
name: 'Learn Stuff',
complete: false
}
})
store.dispatch(addTodoAction({
id: 0,
name: 'Learn More Stuff',
complete: false
}))