https://kotlinlang.org logo
#codereview
Title
# codereview
m

myanmarking

10/21/2021, 3:22 PM
is there any better way of improving this code. For example, using some std extension function idk:
Copy code
fun addChatHeaders(itemList: List<ChatMessage>): List<HelpCenterChatItem> {
    return buildList {
        itemList.forEachIndexed { index, item ->
            val current: ChatMessage = item
            val previous: ChatMessage? = itemList.getOrNull(index - 1)

            if (previous == null || (previous.date.dayOfYear != current.date.dayOfYear)) {
                add(
                    HelpCenterChatItem.HeaderDate(
                        dateFormatter.format(
                            current.date,
                            DatePattern.ISO_DAY_MONTH_YEAR_SLASHED
                        )
                    )
                )
            }
            add(current)
        }
    }
}
p

Paul Griffith

10/21/2021, 3:44 PM
k

Klitos Kyriacou

10/21/2021, 5:01 PM
zipWithNext doesn't work for 1-item lists
p

Paul Griffith

10/21/2021, 5:02 PM
Sure, but if it's a list it's trivial to check if it's 1 item and special-case that
o

Orhan Tozan

10/21/2021, 6:33 PM
Using mapIndexed is cleaner here I think
flatMapIndexed*
r

Roukanken

10/21/2021, 7:21 PM
Under assumption that your list is sorted by date (should be, otherwise your code wouldn't make sense) then some variation of groupBy/flatMap and similar functions can take up the mantle:
Copy code
fun addChatHeaders(itemList: List<ChatMessage>): List<HelpCenterChatItem> {
    return itemList.groupBy { it.date.dayOfYear }
            .flatMap { (dayOfYear, messages) ->
                listOf(HeaderDate(dayOfYear.toString())) + messages
            }
}
I took a tiny shortcut to supply argument for HeaderDate, but this shouldn't be a problem. In fact, just grouping by
it.date
should be better (as it will handle cases when the list spans multiple years), and you can just pass that to formatter then. And yes, groupBy keeps order of the keys in order it first encounters them, from docs:
Copy code
The returned map preserves the entry iteration order of the keys produced from the original collection.
e

ephemient

10/22/2021, 3:38 AM
if stdlib had https://youtrack.jetbrains.com/issue/KT-8280 then the original could be expressed more straightforwardly
m

myanmarking

10/22/2021, 11:24 AM
@Roukanken you are right about everything. Thanks!
4 Views