commonMain.dev.inmo.micro_utils.pagination.utils.Paginate.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of micro_utils.pagination.common-jvm Show documentation
Show all versions of micro_utils.pagination.common-jvm Show documentation
It is set of projects with micro tools for avoiding of routines coding
package dev.inmo.micro_utils.pagination.utils
import dev.inmo.micro_utils.pagination.*
fun Iterable.paginate(with: Pagination): PaginationResult {
var i = 0
val result = mutableListOf()
val lowerIndex = with.firstIndex
val greatestIndex = with.lastIndex
for (item in this) {
when {
i < lowerIndex || i > greatestIndex -> i++
else -> {
result.add(item)
i++
}
}
}
return result.createPaginationResult(with, i.toLong())
}
fun List.paginate(with: Pagination): PaginationResult {
if (with.firstIndex >= size || with.lastIndex < 0) {
return emptyPaginationResult(with, size.toLong())
}
return asSequence().drop(with.firstIndex).take(with.size).toList().createPaginationResult(
with,
size.toLong()
)
}
fun List.paginate(with: Pagination, reversed: Boolean): PaginationResult {
return if (reversed) {
val actualPagination = with.optionallyReverse(
size,
reversed
)
paginate(actualPagination).changeResultsUnchecked { results.reversed() }
} else {
paginate(with)
}
}
fun Set.paginate(with: Pagination): PaginationResult {
return this.drop(with.firstIndex).take(with.size).createPaginationResult(
with,
size.toLong()
)
}
fun Set.paginate(with: Pagination, reversed: Boolean): PaginationResult {
val actualPagination = with.optionallyReverse(
size,
reversed
)
val firstIndex = maxOf(actualPagination.firstIndex, 0)
val lastIndex = minOf(actualPagination.lastIndexExclusive, size)
if (firstIndex > lastIndex) {
return emptyPaginationResult()
}
return this.drop(firstIndex).take(lastIndex - firstIndex).optionallyReverse(reversed).createPaginationResult(
with,
size.toLong()
)
}