-
Notifications
You must be signed in to change notification settings - Fork 0
/
paginator.ts
97 lines (75 loc) · 2.25 KB
/
paginator.ts
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
import { GToolsConfig } from "../config/gtools-config";
export class Paginator<T = unknown> {
private actList: T[];
private actualPage = 0;
private readonly lastPage: number;
public constructor(private readonly allItems: T[],
private readonly itemsPerPage = GToolsConfig.PAGE_LIMIT) {
this.lastPage = allItems ? Math.floor(allItems.length / this.itemsPerPage) : 0;
this.actList = this._reCalcList();
}
public getActualPage(): number {
return this.actualPage + 1;
}
public getPages(): number {
return this.lastPage + 1;
}
public getPagesAround(): number[] {
if (this.actualPage < 2) {
return [1, 2, 3, 4, 5];
}
if (this.actualPage > this.lastPage - 3) {
return [
this.lastPage - 3,
this.lastPage - 2,
this.lastPage - 1,
this.lastPage,
this.lastPage + 1,
];
}
return [
this.actualPage - 1,
this.actualPage,
this.actualPage + 1,
this.actualPage + 2,
this.actualPage + 3,
];
}
public getList(): T[] {
return this.actList;
}
public goToNext(): T[] {
if (this.actualPage < this.lastPage) {
this.actualPage++;
return this._reCalcList();
}
return this.getList();
}
public gotTo(page: number): T[] {
if (page >= 0 && page <= this.lastPage) {
this.actualPage = page;
return this._reCalcList();
}
return this.getList();
}
public goToPrev(): T[] {
if (this.actualPage > 0) {
this.actualPage--;
return this._reCalcList();
}
return this.getList();
}
public goToFirst(): T[] {
this.actualPage = 0;
return this._reCalcList();
}
public goToLast(): T[] {
this.actualPage = this.lastPage;
return this._reCalcList();
}
private _reCalcList(): T[] {
const start = this.actualPage * this.itemsPerPage;
this.actList = this.allItems ? this.allItems.slice(start, start + this.itemsPerPage) : [];
return this.actList;
}
}