All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.dev.inmo.micro_utils.pagination.utils.Paginate.kt Maven / Gradle / Ivy

There is a newer version: 0.22.2
Show newest version
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()
    )
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy