-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
108 lines (95 loc) · 2.3 KB
/
Copy pathindex.ts
File metadata and controls
108 lines (95 loc) · 2.3 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
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
enum IndexType {
ZERO_BASED,
ONE_BASED,
}
const calculateVisiblePages = (
page: number,
firstPage: number,
lastPage: number,
maxPages: number
): number[] => {
const range = Math.floor(maxPages / 2)
let lowerBound = firstPage
let lowerBoundRest = 0
let upperBound = lastPage
let upperBoundRest = 0
if (page - range >= 1) {
lowerBound = page - range
} else {
lowerBoundRest = (page - range - 1) * -1
}
if (page + range <= lastPage) {
upperBound = page + range
} else {
upperBoundRest = (lastPage - range - page) * -1
}
if (upperBoundRest > 0) {
lowerBound =
lowerBound - upperBoundRest > 0 ? lowerBound - upperBoundRest : firstPage
}
if (lowerBoundRest > 0) {
upperBound =
upperBound + lowerBoundRest < lastPage
? upperBound + lowerBoundRest
: lastPage
}
const pages = []
for (let i = lowerBound; i <= upperBound; i++) {
pages.push(i)
}
return pages
}
const calculatePagination = (
page: number,
size: number,
total: number,
config?: {
indexType?: IndexType
maxPages?: number
}
): {
previous: {
indexNumber: number
isDisabled: boolean
}
next: {
indexNumber: number
isDisabled: boolean
}
pages: {
indexNumber: number
displayNumber: number
isCurrent: boolean
}[]
} | null => {
if (total <= size) {
return null
}
const indexType = config?.indexType ?? IndexType.ONE_BASED
const maxPages = config?.maxPages ?? 5
const firstPage = indexType === IndexType.ZERO_BASED ? 0 : 1
const lastPage = Math.ceil(total / size) + (firstPage - 1)
const isCurrentTheFirstPage = page === firstPage
const isCurrentTheLastPage = page === lastPage
return {
previous: {
indexNumber: isCurrentTheFirstPage ? firstPage : page - 1,
isDisabled: isCurrentTheFirstPage,
},
next: {
indexNumber: isCurrentTheLastPage ? lastPage : page + 1,
isDisabled: isCurrentTheLastPage,
},
pages: calculateVisiblePages(page, firstPage, lastPage, maxPages).map(
(visiblePage) => {
return {
indexNumber: visiblePage,
displayNumber:
indexType === IndexType.ZERO_BASED ? visiblePage + 1 : visiblePage,
isCurrent: visiblePage === page,
}
}
),
}
}
export { calculatePagination, IndexType }