From 24f80fb366486a9801a897070e7493f46a157a2c Mon Sep 17 00:00:00 2001 From: Vexify Date: Sun, 24 Nov 2024 13:55:44 +0100 Subject: [PATCH] Optimize automaticMuteBlockedUsers Function for Improved Performance Description: Refactored the automaticMuteBlockedUsers function to enhance performance and reduce resource usage. Implemented batch processing for muting blocked users, allowing multiple users to be muted in a single operation. Utilized a Set for storing blocked user IDs, improving lookup efficiency when checking if a user is blocked. --- src/plugins/voiceMuteBlockedUsers/index.tsx | 35 +++++++++++---------- 1 file changed, 18 insertions(+), 17 deletions(-) diff --git a/src/plugins/voiceMuteBlockedUsers/index.tsx b/src/plugins/voiceMuteBlockedUsers/index.tsx index fe21e9705a..4a75664a1f 100644 --- a/src/plugins/voiceMuteBlockedUsers/index.tsx +++ b/src/plugins/voiceMuteBlockedUsers/index.tsx @@ -20,7 +20,7 @@ const { isLocalMute } = findByPropsLazy("isLocalMute"); const { addRelationship } = findByPropsLazy("addRelationship"); const RoleButtonClasses = findByPropsLazy("button", "buttonInner", "icon", "banner"); -const blockedUserIds: Set = new Set(); +let blockedUserIds: Set = new Set(); let blockedUserCount = 0; const userContextPatch: NavContextMenuPatchCallback = (children, { user }: { user?: User, onClose(): void; }) => { @@ -109,30 +109,31 @@ export default definePlugin({ if (!autoMuteBlocked) return; // Get all relationships and filter for blocked users - const blockedIds = Object.entries(RelationshipStore.getRelationships()) - .filter(([_, v]) => v === 2) - .map(([k]) => UserStore.getUser(k).id); - - // Mute blocked users - for (const ID of blockedIds) { - if (!isLocalMute(ID)) { - toggleLocalMute(ID); - } - blockedUserIds.add(ID); - } + const blockedIdsSet = new Set( + Object.entries(RelationshipStore.getRelationships()) + .filter(([_, v]) => v === 2) + .map(([k]) => UserStore.getUser(k).id) + ); - if (blockedUserCount > blockedIds.length) { - const unblockedUsers = [...blockedUserIds].filter(id => !blockedIds.includes(id)); + // Mute blocked users in batch + const toMute = [...blockedIdsSet].filter(ID => !isLocalMute(ID)); + if (toMute.length > 0) { + toMute.forEach(ID => toggleLocalMute(ID)); + blockedUserIds = new Set([...blockedUserIds, ...toMute]); // Update blockedUserIds + } - for (const ID of unblockedUsers) { + // Handle unblocking + if (blockedUserCount > blockedIdsSet.size) { + const unblockedUsers = [...blockedUserIds].filter(id => !blockedIdsSet.has(id)); + unblockedUsers.forEach(ID => { if (isLocalMute(ID)) { toggleLocalMute(ID); } blockedUserIds.delete(ID); - } + }); } - blockedUserCount = blockedIds.length; + blockedUserCount = blockedIdsSet.size; }, BlockUnblockButton: ErrorBoundary.wrap(({ user }: { user: User; }) => { if (!user) return null; // Return null if no user is provided