-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReduxHelper.js
102 lines (88 loc) · 3.3 KB
/
ReduxHelper.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
export const ReduxArrayHelper = {
append: (list, payload) => {
if(!list || !Array.isArray(list)) return [payload]
let newList = Array.from(list)
newList.push(payload)
return newList
},
prepend: (list, payload) => {
if(!list || !Array.isArray(list)) return [payload]
let newList = Array.from(list)
newList.unshift(payload)
return newList
},
insert: (list, payload, index) => {
if(!list || !Array.isArray(list)) return [payload]
let newList = Array.from(list)
newList.splice(index, 0, payload)
return newList
},
update: (list, payload, comparator = 'id') => {
if(!list || !Array.isArray(list) || !payload) return list
return Array.from(list).map(item => {
if (item[comparator] !== payload[comparator]) {
return item
}
return {
...item,
...payload
}
})
},
updateByIndex: (list, payload, index) => {
if(!list || !Array.isArray(list) || !payload) return list
return Array.from(list).map((item, i) => {
if (index !== i) {
return item
}
return {
...item,
...payload
}
})
},
delete: (list, payload, comparator = 'id') => {
if(!list || !Array.isArray(list) || !payload) return list
return list.filter((data) => data[comparator] !== payload[comparator])
},
deleteById: (list, payload, comparator = 'id') => {
if(!list || !Array.isArray(list) || !payload) return list
return list.filter((data) => data[comparator] !== payload)
},
deleteByIndex: (list, payload) => {
if(!list || !Array.isArray(list) || (!payload && payload !== 0)) return list
return list.splice(payload, 1)
},
find: (list, payload, compare = 'id') => {
if(!list || !Array.isArray(list)) return false
return list.find((data) => data[compare] === payload.id)
},
findById: (list, payload, compare = 'id') => {
if(!list || !Array.isArray(list)) return false
return list.find((data) => data[compare] === payload)
},
findIndexById: (list, payload, compare = 'id') => {
if(!list || !Array.isArray(list)) return false
return list.findIndex((data) => data[compare] === payload)
},
toObjectByKey: (list, key = 'id') => {
if(!list || !Array.isArray(list)) return list
let cache = {}
list.forEach(data => {
cache[data[key]] = data
})
return cache
},
groupedToObjectByKey: (list, key = 'id') => {
if(!list || !Array.isArray(list)) return list
let cache = {}
list.forEach(data => {
if(!cache[data[key]]) {
cache[data[key]] = [data]
} else {
cache[data[key]].push(data)
}
})
return cache
}
}