groupMessages method

List<ChatMessageGroup> groupMessages(
  1. List<AbstractChatMessage> messages,
  2. Duration maxDistance
)

Implementation

List<ChatMessageGroup> groupMessages(
    List<AbstractChatMessage> messages, Duration maxDistance) {
  List<List<AbstractChatMessage>> groups = [];
  List<AbstractChatMessage> group = [];
  AbstractChatMessage? lastMessage;
  for (var message in messages) {
    if (lastMessage == null) {
      group.add(message);
      lastMessage = message;
      continue;
    }

    if (message.timestamp.difference(lastMessage.timestamp).abs() >
            maxDistance ||
        lastMessage.senderId != message.senderId) {
      groups.add(group);
      group = [];
    }

    group.add(message);
    lastMessage = message;
  }

  if (group.isNotEmpty) {
    groups.add(group);
  }

  return groups.map((e) => ChatMessageGroup(e, this)).toList();
}