is there any better way of improving this code. Fo...
# codereview
m
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
k
zipWithNext doesn't work for 1-item lists
p
Sure, but if it's a list it's trivial to check if it's 1 item and special-case that
o
Using mapIndexed is cleaner here I think
flatMapIndexed*
r
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
if stdlib had https://youtrack.jetbrains.com/issue/KT-8280 then the original could be expressed more straightforwardly
m
@Roukanken you are right about everything. Thanks!