Skip to content

Instantly share code, notes, and snippets.

@yapalenov
Last active February 1, 2022 15:06
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yapalenov/1acb0b60a3192aac43924ee44fbfb40b to your computer and use it in GitHub Desktop.
Save yapalenov/1acb0b60a3192aac43924ee44fbfb40b to your computer and use it in GitHub Desktop.
Create pagination buttons array
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