JSFiddle - React, Tailwind, and code Playground
by shapeshifta
JavaScript
function generatePagination(current = 1, last = 1) {
const delta = 2,
left = current - delta,
right = current + delta + 1,
range = {},
rangeWithDots = {};
for (let i = 1; i <= last; i++) {
if (i === 1 || i === last || i >= left && i < right) {
range[i] = i;
}
}
let l;
for (const i in range) {
if (l) {
if (i - l === 2) {
console.log('first')
rangeWithDots[i] = {
text: l + 1
};
} else if (i - l !== 1) {
console.log('second')
rangeWithDots[l] = {
text: '...'
};
}
}
console.log(current, i)
rangeWithDots[i] = {
currentPage: +i === current,
text: i
};
l = i;
}
return rangeWithDots;
}
for (let i = 1, l = 10; i <= l; i++)
console.log(`Selected page ${i}:`, generatePagination(i, l));