Skip to content

Instantly share code, notes, and snippets.

@sarifmiaa
Created January 29, 2020 05:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sarifmiaa/9f64c69757a95f2a34f679e9a330f72a to your computer and use it in GitHub Desktop.
Save sarifmiaa/9f64c69757a95f2a34f679e9a330f72a to your computer and use it in GitHub Desktop.
Generate pagination number
/**
* Generate pagination.
* @param {number} current Current page.
* @param {number} last Last page.
* @param {number} width width.
* @returns {Array} Returns array of pages.
*/
const paginationGenerator = (current, last, width = 2) => {
const left = current - width;
const right = current + width + 1;
const range = [];
const rangeWithDots = [];
let l;
for (let i = 1; i <= last; i += 1) {
if (i === 1 || i === last || (i >= left && i <= right)) {
range.push(i);
} else if (i < left) {
i = left - 1;
} else if (i > right) {
range.push(last);
break;
}
}
range.forEach(i => {
if (l) {
if (i - l === 2) {
rangeWithDots.push(l + 1);
} else if (i - l !== 1) {
rangeWithDots.push('...');
}
}
rangeWithDots.push(i);
l = i;
});
return rangeWithDots;
};
/*
Test Result:
Current page 1: 1,2,3,4,...,30
Current page 2: 1,2,3,4,5,...,30
Current page 3: 1,2,3,4,5,6,...,30
Current page 4: 1,2,3,4,5,6,7,...,30
Current page 5: 1,2,3,4,5,6,7,8,...,30
Current page 6: 1,...,4,5,6,7,8,9,...,30
Current page 7: 1,...,5,6,7,8,9,10,...,30
Current page 8: 1,...,6,7,8,9,10,11,...,30
Current page 9: 1,...,7,8,9,10,11,12,...,30
Current page 10: 1,...,8,9,10,11,12,13,...,30
Current page 11: 1,...,9,10,11,12,13,14,...,30
Current page 12: 1,...,10,11,12,13,14,15,...,30
Current page 13: 1,...,11,12,13,14,15,16,...,30
Current page 14: 1,...,12,13,14,15,16,17,...,30
Current page 15: 1,...,13,14,15,16,17,18,...,30
Current page 16: 1,...,14,15,16,17,18,19,...,30
Current page 17: 1,...,15,16,17,18,19,20,...,30
Current page 18: 1,...,16,17,18,19,20,21,...,30
Current page 19: 1,...,17,18,19,20,21,22,...,30
Current page 20: 1,...,18,19,20,21,22,23,...,30
Current page 21: 1,...,19,20,21,22,23,24,...,30
Current page 22: 1,...,20,21,22,23,24,25,...,30
Current page 23: 1,...,21,22,23,24,25,26,...,30
Current page 24: 1,...,22,23,24,25,26,27,...,30
Current page 25: 1,...,23,24,25,26,27,28,29,30
Current page 26: 1,...,24,25,26,27,28,29,30
Current page 27: 1,...,25,26,27,28,29,30
Current page 28: 1,...,26,27,28,29,30
Current page 29: 1,...,27,28,29,30
Current page 30: 1,...,28,29,30
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment