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
}
wbertan
07/10/2019, 12:15 PMfun <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)
}
Dominaezzz
07/10/2019, 2:53 PMList(capacity) { this.getOrElse(it) { element } }
padEnd
.myanmarking
07/10/2019, 2:56 PM