From 06a07547d88eda6c6911ff8604109422fcadab1a Mon Sep 17 00:00:00 2001 From: Joop Kiefte Date: Wed, 15 Dec 2021 00:03:03 +0000 Subject: Add trim functionality --- message/message.go | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) (limited to 'message') diff --git a/message/message.go b/message/message.go index 7a1699d..4c0fc71 100644 --- a/message/message.go +++ b/message/message.go @@ -158,6 +158,25 @@ func MessagesFromIPFS(cid string) (*Messages, error) { return &messages, nil } +// Trim the Messages map to the given number of messages based on the importance of the messages +func (m *Messages) Trim(n int) { + // Create a slice of Messages sorted by importance + // Cannot lock the Messages map yet, Messages.MessageList() will lock it + msgs := m.MessageList() + // Now lock the Messages map and trim the map to the given number of messages + m.lock.Lock() + defer m.lock.Unlock() + // If the number of messages is less than or equal to the number of messages to keep, do nothing + if len(msgs) <= n { + return + } + fmt.Println("Trimming messages") + // Otherwise, remove the messages after the nth message from the map + for i := n; i < len(msgs); i++ { + delete(m.msgs, msgs[i].Stamp()) + } +} + // Add a message to the Messages map func (m *Messages) Add(msg *Message) { m.lock.Lock() -- cgit v1.2.3-70-g09d2