namespace NadekoBot.Services; public class GreetGrouper { private readonly Dictionary> group; private readonly object locker = new(); public GreetGrouper() => group = new(); /// /// Creates a group, if group already exists, adds the specified user /// /// Id of the server for which to create group for /// User to add if group already exists /// public bool CreateOrAdd(ulong guildId, T toAddIfExists) { lock (locker) { if (group.TryGetValue(guildId, out var list)) { list.Add(toAddIfExists); return false; } group[guildId] = new(); return true; } } /// /// Remove the specified amount of items from the group. If all items are removed, group will be removed. /// /// Id of the group /// Maximum number of items to retrieve /// Items retrieved /// Whether the group has no more items left and is deleted public bool ClearGroup(ulong guildId, int count, out IEnumerable items) { lock (locker) { if (group.TryGetValue(guildId, out var set)) { // if we want more than there are, return everything if (count >= set.Count) { items = set; group.Remove(guildId); return true; } // if there are more in the group than what's needed // take the requested number, remove them from the set // and return them var toReturn = set.TakeWhile(item => count-- != 0).ToList(); foreach (var item in toReturn) set.Remove(item); items = toReturn; // returning falsemeans group is not yet deleted // because there are items left return false; } items = Enumerable.Empty(); return true; } } }