From 53fda8c1179d92a5674d9a32a8f95320bd49ea36 Mon Sep 17 00:00:00 2001 From: hurali97 Date: Fri, 10 May 2024 13:45:20 +0500 Subject: [PATCH] perf: use one loop instead of three for cache collection --- lib/OnyxUtils.ts | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/lib/OnyxUtils.ts b/lib/OnyxUtils.ts index 0c919f64..e0649685 100644 --- a/lib/OnyxUtils.ts +++ b/lib/OnyxUtils.ts @@ -402,18 +402,22 @@ function addAllSafeEvictionKeysToRecentlyAccessedList(): Promise { } function getCachedCollection(collectionKey: TKey, collectionMemberKeys?: string[]): NonNullable> { - const resolvedCollectionMemberKeys = collectionMemberKeys || Array.from(cache.getAllKeys()).filter((storedKey) => isCollectionMemberKey(collectionKey, storedKey)); - - return resolvedCollectionMemberKeys.reduce((prev: NonNullable>, key) => { - const cachedValue = cache.getValue(key); - if (!cachedValue) { - return prev; + const allKeys = collectionMemberKeys || cache.getAllKeys(); + const collection: OnyxCollection = {}; + + // forEach exists on both Set and Array + allKeys.forEach((key) => { + // If we don't have collectionMemberKeys array then we have to check whether a key is a collection member key. + // Because in that case the keys will be coming from `cache.getAllKeys()` and we need to filter out the keys that + // are not part of the collection. + if (!collectionMemberKeys && !isCollectionMemberKey(collectionKey, key)) { + return; } - // eslint-disable-next-line no-param-reassign - prev[key] = cachedValue; - return prev; - }, {}); + collection[key] = cache.getValue(key); + }); + + return collection; } /**