https://kotlinlang.org logo
Title
m

myanmarking

07/10/2019, 10:53 AM
/**
 * Returns a new list of size [capacity] with elements from the original list, filled with [element] if needed
 */
fun <E> List<E>.fillWith(capacity: Int, element: E?): List<E?> {
    val outList = mutableListOf<E?>()
    repeat(capacity){ outList.add(element) }

    if(this.isEmpty()) return outList

    val sl = this.subList(0, min(capacity, this.size))

    sl.forEachIndexed { index, e ->
        outList[index] = e
    }
    return outList
}
w

wbertan

07/10/2019, 12:15 PM
Is it possible to you give some test cases?
fun <T> List<T>.fillWith(capacity: Int, element: T?): List<T?> =
            when {
                size >= capacity -> this
                else -> this + List(capacity - size) { element }
            }

    @Test
    fun `given capacity less than the size when fill it should return original list`() {
        val l1 = listOf(1, 2, 3)
        val result = l1.fillWith(1, 0)
        assertEquals(listOf(1, 2, 3), result)
    }

    @Test
    fun `given capacity same as the size when fill it should return original list`() {
        val l1 = listOf(1, 2, 3)
        val result = l1.fillWith(3, 0)
        assertEquals(listOf(1, 2, 3), result)
    }

    @Test
    fun `given capacity more than the size when fill it should return list appended with element until the new capacity`() {
        val l1 = listOf(1, 2, 3)
        val result = l1.fillWith(5, 0)
        assertEquals(listOf(1, 2, 3, 0, 0), result)
    }
d

Dominaezzz

07/10/2019, 2:53 PM
List(capacity) { this.getOrElse(it) { element } }
I think you're looking for a function called
padEnd
.
m

myanmarking

07/10/2019, 2:56 PM
yes, padEnd will do. thank you!