Practical use of coerceAtLeast

21 Jun, 2020

Kotlin language provides many useful functions. Today we will look at coerceAt* functions. coerceAt* functions are used to clamp values, which works quite similar to min/max.

coerceAtLeast comes out quite handy when we need to compute estimated time of arrival (ETA) as min and max bounds.

//import java.util.concurrent.TimeUnit

/**
 * Compute ETA as min-max range
 */
fun computeMinMaxEtaRange(departureDelayInMillis: Long): String {
    // convert time in millis to minutes
    val etaInMin = TimeUnit.MILLISECONDS.toMinutes(departureDelayInMillis)
    val range = 5.0
    val ceil = Math.ceil(etaInMin / range)	   
    val maxToNearestFive = range.coerceAtLeast(range * ceil).toInt()	    
    val minBound = maxToNearestFive - 4	     
    return "$minBound - $maxToNearestFive"
}

// Input: 845600
// Output: 11 - 15

Copyright © 2020. All rights reserved.Powered by Gatsby