Last active
February 1, 2022 15:06
-
-
Save yapalenov/1acb0b60a3192aac43924ee44fbfb40b to your computer and use it in GitHub Desktop.
Create pagination buttons array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Pagination { | |
private readonly page: number; | |
private readonly pagesCount: number; | |
private readonly delta: number; | |
constructor(page: number, pagesCount: number) { | |
this.page = page; | |
this.pagesCount = pagesCount; | |
this.delta = 2; | |
} | |
range = function* (start = 0, end = 0) { | |
while (start <= end) { | |
yield start++; | |
} | |
}; | |
getButtons = () => { | |
const buttons = []; | |
const before = this.page - this.delta > 1; | |
const after = this.page + this.delta < this.pagesCount; | |
const start = Math.max( | |
before | |
? this.page - | |
this.delta - | |
(!after ? this.page - this.pagesCount + 1 + this.delta : 0) | |
: 2, | |
2 | |
); | |
const end = Math.min( | |
after | |
? this.page + | |
this.delta + | |
(!before ? 2 - this.page + this.delta : 0) | |
: this.pagesCount - 1, | |
this.pagesCount - 1 | |
); | |
buttons.push(1); | |
for (const i of this.range(start, end)) { | |
buttons.push(i); | |
} | |
if (this.pagesCount !== 1) { | |
buttons.push(this.pagesCount); | |
} | |
return buttons; | |
}; | |
} | |
const pagination = new Pagination(35, 40); | |
const buttons = pagination.getButtons(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment