I need something like `fun getPartRanges(partSize:...
# getting-started
d
I need something like
fun getPartRanges(partSize: Long, totalSize: Long): List<LongRange>
that returns something like [0..20,21..40,41..60,61..74] for an input of
partSize = 20
and
totalSize = 74
, what is an ideomatic way to do this in Kotlin?
r
There's maybe no idiomatic ways to do that, but you can implement it simply yourself.
Idk what you wanna do in your code, but functions
chunked
or
windowed
may help.
d
That's what I was wondering?
k
(0 until totalSize).chunked(partSize)
(if
totalSize
and
partSize
are actual sizes contrary to your example, otherwise it's
..
instead of
until
.
r
@karelpeeters The range will be iterated totally, and it can be avoided in a better implementation.
k
Put a
toSequence
in there if you want.
d
Just about to say that, the Long is a file size and the range is the current range of the file that needs to be downloaded...
So it could be 60mb in a bytes Long and iterate to get a list of all the numbers in between instead of just returning from where to start and where to end the current download @karelpeeters...
But I thought there might at least be a few things in stdlib that could help... maybe reduce?
k
(0 .. totalSize/partSize).map { it .. min((1 + it) * partSize, totalSize }
r
A little long, you can try this if you don't mind.
Copy code
fun getPartRanges(partSize: Long, totalSize: Long): List<LongRange> {
    val fullPartCount = (totalSize / partSize).toInt()
    val perfect = totalSize % partSize == 0L
    val partRanges = ArrayList<LongRange>(fullPartCount + if (perfect) 0 else 1)

    var current = 0L
    var next = partSize
    while (next < totalSize) {
        partRanges += current until next
        current = next
        next += partSize
    }

    if (!perfect) partRanges += current until totalSize

    return partRanges
}
k
Idiomatic
Writes the most procedural code possible 😉
d
Thanks, I'll give those a try simple smile .....
@karelpeeters Looks like
(0L .. totalSize/partSize).map { (it * partSize) .. min((it * partSize) + partSize + 1, totalSize) }
works! Thanks a lot! And thanks for the try @Ricky, if anything it just goes to show how Kotlin goes a long way 🙂 !