Last active
December 24, 2018 01:10
-
-
Save papalardo/c93636c297f54d791b79ced2385373fb to your computer and use it in GitHub Desktop.
Array paginate interval JS
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
function getInterval(totalItens = 100, perPage = 10, maxShowingNumbers = 5, currentPage = 1) { | |
let lastPage = Math.ceil(totalItens / perPage) | |
if (totalItens < 0 ) { | |
console.error(`Total of itens cant be less or equal than 0`) | |
return; | |
} else if (lastPage > 0 && currentPage > lastPage) { | |
console.error(`Current page [${currentPage}] cant be bigger than last page [${lastPage}]`) | |
return; | |
} | |
function getRange(start, end, step = 1) { | |
let len = Math.floor((end - start) / step) + 1 | |
return Array(len).fill().map((_, idx) => start + (idx * step)) | |
} | |
let interval = lastPage > 0 | |
? getRange( | |
Math.max(1, Math.min(lastPage - maxShowingNumbers + 1, currentPage)), | |
Math.min(lastPage, Math.min(maxShowingNumbers, lastPage) - 1 + currentPage) | |
) | |
: [] | |
console.log(interval) | |
} | |
-> Outputs | |
getInterval(100, 10, 5, 1) -> (5) [1, 2, 3, 4, 5] | |
getInterval(559, 20, 3, 28) -> (3) [26, 27, 28] | |
getInterval(200, 15, 5, 17) -> Current page [17] cant be bigger than last page [14] | |
getInterval(1, 10, 5, 1) -> [1] | |
getInterval(1000, 10, 5, 100) -> (5) [96, 97, 98, 99, 100] | |
getInterval(0, 10, 5, 10) -> [] | |
getInterval(-1 , 10, 5, 10) -> total itens cant be less than 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment