Last active
January 9, 2019 16:18
-
-
Save brunobertolini/5eb04077a486bb6f279334c962357965 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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