Join to string with truncated middle

38 Views Asked by At

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.

1

There are 1 best solutions below

2
Zeredan Tech On

AS a solution i can suggest that:

fun<T> List<T>.myJoin(leftCount: Int, rightCount: Int) = this.run{(0 until leftCount).toList() + (this.size - rightCount until this.size).toList() }.map{ this[it] }.joinToString(" ")

now you can use it:

println("1 2 5 8 9 10 31 23 1".split(" ").myJoin(3, 4))
//1 2 5 10 31 23 1