https://kotlinlang.org logo
Title
s

Sam Stone

08/12/2022, 5:31 AM
I have a list of timestamps, and want to group them together if they are less than a certain duration apart (map them to the durations they represent, so I can sum the durations to get the total amount of time). I feel like there is a stdlib function on List to do this, but I can’t find it.
e

ephemient

08/12/2022, 5:36 AM
stdlib `groupBy`/`groupingBy` makes sense for equivalence classes where you can define a key. it doesn't sound like that's the case here, so there isn't really anything in stdlib to help
you could do something like this: https://pl.kotl.in/jc1j0eWSV (relies on input being sorted)
j

jw

08/12/2022, 12:28 PM
partition would also work
oh nevermind i re-read the question
ultimately a for loop will probably be the clearest where you keep a last, diff the current, act accordingly, and then update last to current.
s

Sam Stone

08/12/2022, 8:45 PM
But shouldn't there be a function for that? It is such a common pattern/use case.
e

ephemient

08/12/2022, 8:46 PM
see the KT issue in the playground link I made
j

jw

08/12/2022, 8:48 PM
Is it really that common?
I'm sure it feels that way right now since you need it, but it's pretty simple to write yourself and there's myriad missing functions for all kinds of operations other people want but you've never needed.
e

ephemient

08/12/2022, 8:52 PM
I think it's reasonably common - I've written it at least 3 times now, and it's in other langauges' standard libraries