Jérémy CROS
03/27/2024, 4:41 PMlistOfSegments
.takeWhile { it != current }
.reversed()
.takeWhile { it.level() == current.level() }
.reversed()
.flatMap { it.coordinates }
It works but seems rather inefficient. Any idea on how I could improve that?Jacob
03/27/2024, 5:15 PMJacob
03/27/2024, 5:17 PMJacob
03/27/2024, 5:18 PMKlitos Kyriacou
03/27/2024, 5:26 PMlistOfSegments
.subList(0, listOfSegments.indexOf(current))
.asReversed()
.let { list -> list.subList(0, list.indexOfFirst { it.level() != current.level() } }
.asReversed()
.flatMap { it.coordinates }
This can be further simplified:
listOfSegments
.subList(0, listOfSegments.indexOf(current))
.run { subList(indexOfLast { it.level() != current.level() } + 1, size }
.flatMap { it.coordinates }
Vlad Mircan
03/27/2024, 6:06 PMreversed()
calls.
Without doing anything complex, we can improve the performance (and readability) of the code a lot by doing this:
listOfSegments
.takeWhile { it != current }
.takeLastWhile { it.level() == current.level() }
.flatMap { it.coordinates }
Jérémy CROS
03/28/2024, 8:47 AMtakeLastWhile
, that's the one I was looking for! Thanks @Vlad Mircan, I knew there was something better than my double reversed 😅
Thanks @Klitos Kyriacou for the suggestion but the use case is iterating over rather small list so readability is still important and the solution with takeLastWhile
is easier to understand IMO
And thanks @Jacob too but the use case is slightly more complicated than that 😉 the level could be wrong then right then wrong then right then current and I want just the last right before current
Anyway, thanks all, I think I'm all good! 🙏