Skip to content

Instantly share code, notes, and snippets.

@brunobertolini
Last active January 9, 2019 16:18
Show Gist options
  • Save brunobertolini/5eb04077a486bb6f279334c962357965 to your computer and use it in GitHub Desktop.
Save brunobertolini/5eb04077a486bb6f279334c962357965 to your computer and use it in GitHub Desktop.
import * as R from 'ramda'
export const between = (num: number, min: number, max: number) =>
R.max(min, R.min(num, max))
export const paginate = (
records: number,
limit: number = 10,
current: number = 1,
delta: number = 1,
fixed: number = 1
) => {
const total = Math.ceil(R.max(1, records / limit))
const page = between(current, 1, total)
const min = 1 + fixed
const max = total - fixed
const maxLeft = R.min(max - delta * 2 - 1, max)
const minRight = R.min(min + delta * 2 + 1, max)
const left = between(page - delta, min, maxLeft)
const right = between(page + delta, minRight, max)
const missLeft = left - fixed
const missRight = total - fixed - right + 1
const prev = missLeft > 2
const next = missRight > 2
const start = R.range(1, between(fixed + 1, 1, total + 1))
const middle = R.range(
missLeft === 2 ? left - 1 : left,
missRight === 2 ? right + 2 : right + 1
)
const end = R.range(between(total - fixed + 1, 2, total + 1), total + 1)
const from = between(limit * page - limit + 1, 1, records)
const to = between(limit * page, 1, records)
return { total, current: page, start, end, prev, next, middle, from, to }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment