If I have a long list and want to print only the first 6 elements, it's easy:
// Let's say list contains the first few numbers in the Fibonacci sequence
println(list.joinToString(limit = 6)) // output: [0, 1, 1, 2, 3, 5, ...]
But I'd like to show the first 3 and last 3: [0, 1, 1, ..., 55, 89, 144]
Is there a neat way to use joinToString to do that?
Example usage:
listOf(1, 2, 3, 4, 5, 6, 7, 8).truncateToString(6)
-> "1, 2, 3, ..., 6, 7, 8" // 6 elements, 3 from each end
listOf(1, 2, 3, 4, 5, 6, 7).truncateToString(6)
-> "1, 2, 3, 4, 5, 6, 7" // no need to replace a single element
-> "1, 2, 3, ..., 5, 6, 7" // this also acceptable
listOf(1, 2, 3, 4, 5, 6).truncateToString(6)
-> "1, 2, 3, 4, 5, 6" // no truncation if whole list can be rendered
To implement it, I can only think of doing it manually, doing essentially list.take(3) + "..." + list.takeLast(3) but I thought there might be an easier way.
AS a solution i can suggest that:
now you can use it: