Skip to content

Instantly share code, notes, and snippets.

@yuriuliam
Last active July 5, 2024 17:56
Show Gist options
  • Save yuriuliam/6c99368e8057b81446a847a75d4dc972 to your computer and use it in GitHub Desktop.
Save yuriuliam/6c99368e8057b81446a847a75d4dc972 to your computer and use it in GitHub Desktop.
const createPageOptions = ((currentPage, pageCount) => {
// from component properties
const currentPage = currentPage
// from Constants
const NUM_OF_PAGE_OPTIONS = 7
// useMemo with [currentPage] as deps
const pageOptions = (() => {
if (pageCount <= 0) return []
const pages = new Array(pageCount).fill(1).map((e, i) => e + i)
if (pageCount <= NUM_OF_PAGE_OPTIONS) return pages
const firstPage = pages[0]
const lastPage = pages[pages.length - 1]
const pageOffset = Math.min(
Math.max(
Math.ceil(NUM_OF_PAGE_OPTIONS / 2), currentPage
) - Math.floor(NUM_OF_PAGE_OPTIONS / 2),
pageCount - NUM_OF_PAGE_OPTIONS + 1
)
return [
firstPage,
...[...pages].splice(pageOffset, NUM_OF_PAGE_OPTIONS - 2),
lastPage
]
})()
return { pageOptions }
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment