elm-community / list-extra

Convenience functions for working with List.

Home Page:http://package.elm-lang.org/packages/elm-community/list-extra/latest

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Proposal for more context in `groupWhile`

peterszerzo opened this issue · comments

I recently came across the need for a version of groupWhile where the grouping function needs more context than just two adjacent elements.

Use-case

I am rendering the following messages in a chat-like layout:

messages =
  [ { receivedAt = 99, author = "Simon" }
  , { receivedAt = 100, author = "Maria" }
  , { receivedAt = 110, author = "Maria" }
  , { receivedAt = 120, author = "Maria" }
  , { receivedAt = 130, author = "Maria" }
  ]

Messages should be rendered closer together when they have a different author, but also if more than 15 time units elapse within a single group. The current groupWhile would put Maria's messages in the same group despite there being 30 time units between the first and the last message.

Proposed change to groupWhile

(or function under new name)

In the following type definition, both the previous member in the group as well as elements in the group before it show up in the grouping function (in the (List a, a) tuple):

groupWhile : ((List a, a) -> a -> Bool) -> List a -> List (a, List a)

Using this, I can group my messages for rendering as follows:

groupWhile
  (\( beforeInGroup, previous ) current ->
    previous.author == current.author &&
      (List.head beforeInGroup
        |> Maybe.withDefault previous
        |> .receivedAt
        |> (\receivedAt -> abs (receivedAt - current.receivedAt) < 15)
      )
  )
  messages

Hey @peterszerzo

I think this isnt such a good idea for groupWhile. It does make it more general, and therefore cover more usecases (which is good) but I think it also makes it more complicated, and so it makes it harder to use in the normal use case of comparing two adjacent items.

Maybe it would be worthwhile as a separate function? Im not sure. It would need an original name too, if we went down that road.

Thanks for looking at the issue, @Chadtech - I agree with your reasoning, especially if there isn't much interest. I'm considering publishing a library that combines helpers from multiple -extra libraries and a few other things useful in large applications (like a functor for undo-redo), maybe I'll just include a version of groupWhile (with a different name) there.

Thanks for the well written proposal tho.