Total Complexity | 9 |
Complexity/F | 0 |
Lines of Code | 47 |
Function Count | 0 |
Duplicated Lines | 0 |
Ratio | 0 % |
Changes | 0 |
1 | import React from 'react'; |
||
2 | import orderBy from 'lodash/orderBy'; |
||
3 | import { toast } from 'react-toastify'; |
||
4 | |||
5 | export const arrayReducer = (state, action) => { |
||
6 | const { type, id, payload, sortBy, order, isAddToStart, isUpdatedStart } = action; |
||
7 | switch (type) { |
||
8 | case 'ADD': |
||
9 | if (!payload) { |
||
10 | console.error('payload is required!'); |
||
11 | return state; |
||
12 | } |
||
13 | if (state.find(item => item.id === payload.id)) { |
||
14 | toast(<span className="text-warning">Item already exists in the list!</span>); |
||
15 | return state; |
||
16 | } |
||
17 | if (isAddToStart) { |
||
18 | return [payload, ...state]; |
||
19 | } |
||
20 | return [...state, payload]; |
||
21 | case 'REMOVE': |
||
22 | if (id !== 0 && !id) { |
||
23 | console.error('id is required!'); |
||
24 | return state; |
||
25 | } |
||
26 | return state.filter(item => item.id !== id); |
||
27 | case 'EDIT': |
||
28 | if (id !== 0 && !id) { |
||
29 | console.error('id is required!'); |
||
30 | return state; |
||
31 | } |
||
32 | if (isUpdatedStart) { |
||
33 | const filteredState = state.filter(item => item.id !== id); |
||
34 | return [payload, ...filteredState]; |
||
35 | } |
||
36 | return state.map(item => (item.id === id ? payload : item)); |
||
37 | case 'SORT': |
||
38 | if (!sortBy || !order) { |
||
39 | console.error('sortBy and order, both are required!'); |
||
40 | return state; |
||
41 | } |
||
42 | return orderBy(state, sortBy, order); |
||
43 | default: |
||
44 | return state; |
||
45 | } |
||
46 | }; |
||
47 |