-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfilterReducer.js
118 lines (97 loc) · 2.8 KB
/
filterReducer.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
const filterReducer = (state, action) => {
switch (action.type) {
case "LOAD_FILTER_PRODUCTS":
let priceArr = action.payload.map((curElem) => curElem.price);
let maxPrice = Math.max(...priceArr);
return {
...state,
filter_products: [...action.payload],
all_products: [...action.payload],
filters: { ...state.filters, maxPrice, price: maxPrice },
};
case "SET_GRID_VIEW":
return {
...state,
grid_view: true,
};
case "GET_SORT_VALUE":
return {
...state,
sorting_value: action.payload,
};
case "SORTING_PRODUCTS":
let newSortData;
const { filter_products, sorting_value } = state;
let tempSortProduct = [...filter_products];
const sortingProducts = (a, b) => {
if (sorting_value === "lowest") {
return a.price - b.price;
}
if (sorting_value === "highest") {
return b.price - a.price;
}
if (sorting_value === "a-z") {
return a.name.localeCompare(b.name);
}
if (sorting_value === "z-a") {
return b.name.localeCompare(a.name);
}
};
newSortData = tempSortProduct.sort(sortingProducts);
return {
...state,
filter_products: newSortData,
};
case "UPDATE_FILTERS_VALUE":
const { name, value } = action.payload;
return {
...state,
filters: {
...state.filters,
[name]: value,
},
};
case "FILTER_PRODUCTS":
let { all_products } = state;
let tempFilterProduct = [...all_products];
const { text, category, price } = state.filters;
if (text) {
tempFilterProduct = tempFilterProduct.filter((curElem) => {
return curElem.name.toLowerCase().includes(text);
});
}
if (category !== "all") {
tempFilterProduct = tempFilterProduct.filter(
(curElem) => curElem.category === category
);
}
if (price === 0) {
tempFilterProduct = tempFilterProduct.filter(
(curElem) => curElem.price === price
);
} else {
tempFilterProduct = tempFilterProduct.filter(
(curElem) => curElem.price <= price
);
}
return {
...state,
filter_products: tempFilterProduct,
};
case "CLEAR_FILTERS":
return {
...state,
filters: {
...state.filters,
text: "",
category: "all",
maxPrice: 0,
price: state.filters.maxPrice,
minPrice: state.filters.maxPrice,
},
};
default:
return state;
}
};
export default filterReducer;